gson 如何解析包含多个相同类型的JSON对象(不是数组)的JSON对象

0g0grzrc  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(217)

我有一个JSON对象,里面有多个JSON对象,都是相同类型的。我应该如何用GSON解析它?
詹森:

{
"people":{
      "1": {
          "name": "A",
          "age": 5
         },
      "2": {
          "name": "B",
          "age": 6
         },
      "3": {
          "name": "C",
          "age": 7
         }
}
}

考虑到我有这类人

class Person{
   private String name;
   private int age;
}

如何使用GSON将数据解析到数组中?List<Person> people;

hs1rzwqc

hs1rzwqc1#

您需要一个类来表示您的json结构:

class Person {
    private String name;
    private int age;
  }

  class PersonMap {
    private Map<String, Person> people;
  }

  @Test
  public void test() {
    String json =
        "{\r\n"
            + "\"people\":{\r\n"
            + "      \"1\": {\r\n"
            + "          \"name\": \"A\",\r\n"
            + "          \"age\": 5\r\n"
            + "         },\r\n"
            + "      \"2\": {\r\n"
            + "          \"name\": \"B\",\r\n"
            + "          \"age\": 6\r\n"
            + "         },\r\n"
            + "      \"3\": {\r\n"
            + "          \"name\": \"C\",\r\n"
            + "          \"age\": 7\r\n"
            + "         }\r\n"
            + "}\r\n"
            + "}";

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    var persons = gson.fromJson(json, PersonMap.class).people.values();
    for (Person person : persons) {
      System.out.println(person.name + " " + person.age);
    }
  }

相关问题