Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 930
membersound Avatar asked Apr 20 '15 11:04

membersound


3 Answers

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;
}
like image 191
cнŝdk Avatar answered Oct 23 '22 14:10

cнŝdk


Try this:

@JsonProperty("message")
private String value;
like image 33
kamil.rak Avatar answered Oct 23 '22 16:10

kamil.rak


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);
like image 1
bhdrkn Avatar answered Oct 23 '22 15:10

bhdrkn