简体   繁体   中英

Jackson deserialize objects with root key

I want to deserialize JSON using Java:

{  
   "Smith":{  
      "id":1,
      "age": 20
   },
   "Carter":{  
      "id":2,
      "age": 21
   }
}

to a list of objects of this class:

class Person {
    private Long id;
    private Integer age;
    private String name; //here I want to have eg. Smith

    //getters and setters
}

How to do this?

ObjectMapper map = new ObjectMapper();
String json ="your json here " 
Person person = map.readValue(json, Person.class);

This is the standard method, in your case your json seems bit different , so you have to create a pojo class which is matching to your JSON

This would be through mapping, (in this specific case) for instance:

Person myPerson = new ObjectMapper().readValue(YOURJSONHERE, Person.class);

The mapper will map the properties specified in your Person model, to the corresponding fields in the JSON. If you have any problems try looking here

However, the way your JSON is structured suggests it would map to a class 'Smith' or 'Carter', the correct format for using the mapper would therefore be:

{
 "Person":{
     "name":"Smith",
     "id": 1,
     "age": 20
  }
}

Using gson is quite simple:

Type type = new TypeToken<List<Person>>() {}.getType();
Gson gson = new GsonBuilder().create();
List<Person> person = gson.fromJson(yourJson, type);

This is a rough working example not following best practices but if you use Jackson elsewhere you should be able to figure it out. You can also register a custom module that can use this same logic for you if its serialized this way in other places as well.

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    static class Person {
        private Long id;
        private Integer age;
        private String name; //here I want to have eg. Smith

        public Person() {

        }

        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
        }
    }

    public static void main(String[] args) throws JsonProcessingException, IOException {
        String json = "{  \n" +
                "   \"Smith\":{  \n" +
                "      \"id\":1,\n" +
                "      \"age\": 20\n" +
                "   },\n" +
                "   \"Carter\":{  \n" +
                "      \"id\":2,\n" +
                "      \"age\": 21\n" +
                "   }\n" +
                "}";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode nodes = mapper.readTree(json);

        List<Person> people = new ArrayList<>();
        nodes.fields().forEachRemaining(entry -> {
            String name = entry.getKey();
            Person person = mapper.convertValue(entry.getValue(), Person.class);
            person.setName(name);
            people.add(person);
        });

        for (Person person : people) {
            System.out.println(person);
        }
    }
}

Output

Person [id=1, age=20, name=Smith]
Person [id=2, age=21, name=Carter]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM