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

Time:12-15

I have a JSON Object with multiple JSON objects within it, all of the same type. How should I parse it with GSON ?

Json :

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

Consider I have this class Person

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

How should I use GSON to parse data into an array? List<Person> people;

CodePudding user response:

You need a class that represents your json structure:

  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);
    }
  }
  • Related