简体   繁体   English

将Java字段映射到JSON文档根目录

[英]Map Java field to JSON document root

I couldn't find an example how to map the following json: 我找不到如何映射以下json的示例:

{
"id":1,
"name":"hugodesmarques",
"age":30,
}

To the following java object using jackson: 使用杰克逊到以下java对象:

public class EntityDto {
   private Map<String, Object> content;
}

Notice the dto is just a wrapper. 注意dto只是一个包装器。 What I'm trying to achieve is to have an object EntityDto with a Map{name=>"hugodesmarques", age=>30, id=>1}. 我想要实现的是让一个对象EntityDto与Map {name =>“ hugodesmarques”,age => 30,id => 1}。

I want to avoid having to map each json field to an object map. 我想避免将每个json字段映射到一个对象映射。

Structure of class must be like structure of JSON: 类的结构必须类似于JSON的结构:

public class EntityDto {
   int id;
   String name;
   int age;
}

Jackson can read JSON as a HashMap: Jackson可以将JSON作为HashMap读取:

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue("{\"id\":1, \"name\": \"One\"}", HashMap.class);
    EntityDto dto = new EntityDto();
    dto.setContent(map);

A step back 退后一步

First of all, the JSON you posted in you question is invalid : there's a comma after 30 and it shouldn't be there. 首先,您在问题中发布的JSON 无效30以后有一个逗号,并且不应在其中。 Fix your JSON otherwise Jackson won't parse it: 修复您的JSON,否则Jackson不会解析它:

{
  "id": 1,
  "name": "hugodesmarques",
  "age": 30
}

Parsing the JSON with Jackson 用Jackson解析JSON

Add a constructor annotated with @JsonCreator to the EntityDto class, as following: 将带有@JsonCreator注释的构造函数添加到EntityDto类,如下所示:

public class EntityDto {

    private Map<String, Object> content;

    @JsonCreator
    public EntityDto(Map<String, Object> content) {
        this.content = content;
    }

    // Getters and setters omitted
}

Then parse the JSON using ObjectMapper : 然后使用ObjectMapper解析JSON:

String json = "{\"id\":1,\"name\":\"hugodesmarques\",\"age\":30}";

ObjectMapper mapper = new ObjectMapper();
EntityDto entityDto = mapper.readValue(json, EntityDto.class);

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

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