gson 如何从嵌套JSON中获取数据?

fkvaft9z  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(265)

下面是我的代码:

public class Parser {
private static final String PATH = "try.json";

public static void main(String[] args) throws IOException, ParseException {

    String req = FileUtils.readFileToString(new File(PATH), StandardCharsets.UTF_8);

    Bean data = new Gson().fromJson(req, Bean.class);
public class Bean{
    private List<Data> data;

    public List<Data> getData() {
        return data;
    }

public class Data {

    private List<String> urls;
    private String name;
    private String type;
    private String picture;

    public List<String> getUrls() {
        return urls;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public String getPicture() {
        return picture;
    }

}

下面是虚拟JSON:

{
    "data": [
      {
            "urls": [
            "https://google.com",
            "https://googl.com"
            ],
            "name": "Google",
            "type": "corp",
            "picture": "https://google.img"
      },
      {
            "urls": [
            "https://yandex.ru"
            ],
            "name": "Yandex",
            "type": "corp",
            "picture": "https://yandex.jpg"
      }
    ]
}

这里的主要使命是-从json创建一个包含“name”字段和“urls”ArrayList的对象,然后我将它们添加到另一个列表中,并通过索引获取信息。但我就是不明白,我该怎么做。例如,对于第一个对象的响应应该是这样的:

Google
"https://google.com",
"https://googl.com"
7rtdyuoh

7rtdyuoh1#

如果我没理解错的话,你想要一个循环

Bean data = new Gson().fromJson(req, Bean.class);
 for (Data d : data.getData()) {
   System.out.println(d.getName());
   for (String u : d.getUrls()) {
     System.out.println(u);
   }
 }

否则,您已经可以通过索引访问内容

Data first = data.getData().get(0);
System.out.println(first.getName()); // google
jljoyd4f

jljoyd4f2#

好吧,如果GSON的使用对你来说不是强制性的,你可以使用Jackson。
通过使用@JsonProperty注解,您可以获得嵌套字段,如果需要,您还可以使用@JsonAlias添加一些别名。
下面是一个简短的示例:

import com.fasterxml.jackson.annotation.JsonProperty;

    public class Data {

    private List<String> urls;
    private String name;
    private String type;
    private String picture;

    public List<String> getUrls() {
        return urls;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public String getPicture() {
        return picture;
    }

}
    @JsonProperty("ParentObject") //Here it looks like the parent object is an element of the array Data, so i would treat you Json object as a list of objects and iterate over each.
    private void getFieldNestedValues(Map<String, String> field) {
        urls = field.get("nestedField1"); //nestedField1 would be urls in your case
        name = field.get("nestedField2"); // nestedField2 could be the name for instance
    }

我很肯定你也可以用Gson做同样的事情,希望这个例子能给你一个想法,告诉你如何让它工作。
编辑:忘了提到我将使用Jackson库中的ObjectMapper来解析和构建对象:

JsonNode rootNode = objectMapperProvider.buildSureObjectMapper().readTree(jsonBody);

 YourObject yourObject= objectMapperProvider.buildSureObjectMapper().readValue(rootNode.toString(), YourObject.class);

例如,使用自定义ObjectMapper:

public ObjectMapper buildSureObjectMapper() {
    return new ObjectMapper()
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule())
            .registerModule(new GuavaModule())
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
            .setSerializationInclusion(NON_ABSENT);
}

相关问题