How to map JSON fields to custom object properties? [duplicate]

那年仲夏 提交于 2019-12-05 18:09:29

问题


I have a simple json message with some fields, and want to map it to a java object using spring-web.

Problem: my target classes fields are named differently than int he json response. How can I anyhow map them to the object without having to rename the fields in java?

Is there some annotation that could be placed here?

{
  "message":"ok"
}

public class JsonEntity {
    //how to map the "message" json to this property?
    private String value;
}

RestTemplate rest = new RestTemplate();
rest.getForObject(url, JsonEntity.class);

回答1:


To map a JSON property to a java object with a different name use @JsonProperty annotation, and your code will be :

public class JsonEntity {
    @JsonProperty(value="message")
    private String value;
}



回答2:


Try this:

@JsonProperty("message")
private String value;



回答3:


In case you familiar it, you can also use Jaxb annotations to marshal/unmarshal json using Jackson

@XmlRootElement
public class JsonEntity {
   @XmlElement(name = "message")
  private String value;
}

But you must initialize your Jackson context propery. Here an example how to initialize Jackson context with Jaxb annotations.

ObjectMapper mapper = new ObjectMapper();

AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);


来源:https://stackoverflow.com/questions/29746303/how-to-map-json-fields-to-custom-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!