jeudi 26 février 2015

Change property names while deserialzing class to JSON in Spring MVC

I'm trying to consume a rest API call using Spring as below:



HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

HttpEntity<String> request = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();

Item item = restTemplate.exchange(url, HttpMethod.GET, request, Item.class).getBody();


The response I get from the API is in following form:



{
"item":[{
"itemname": "abc",
"qty":...
}]
}


The Item class has following fields:



Class Item{
@JsonProperty("itemname")
String name;
@JsonProperty("qty")
int quantity;

// Getter / setter methods
}


I've added JsonProperty annotations to the fields as their names are different from the json I get from the API. With this, I'm able to deserialize the api response successfully.


However, when I try to serialize the Item class again as a json, the field names are "itemname" and "qty". Is there any way to keep these as "name" and "quantity", and yet be able to map to the API response?


Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire