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

How to Parse a JSON object with contains multiple JSON objects ( not an array) of the same type

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

Json :

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

考虑一下我有这个 class 人

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

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

您需要一个 class 代表您的 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);
    }
  }