简体   繁体   English

Jackson用根密钥反序列化对象

[英]Jackson deserialize objects with root key

I want to deserialize JSON using Java: 我想使用Java反序列化JSON:

{  
   "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 这是标准方法,在您的情况下,您的json似乎有点不同,因此您必须创建一个与JSON匹配的pojo类

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. 映射器会将您的Person模型中指定的属性映射到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: 但是,JSON的结构方式建议将其映射到类“ Smith”或“ Carter”,因此使用映射器的正确格式为:

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

Using gson is quite simple: 使用gson非常简单:

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. 这是一个粗糙的工作示例,没有遵循最佳实践,但是如果您在其他地方使用Jackson,您应该可以弄清楚。 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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