Viki Cullen Viki Cullen - 4 months ago 11
JSON Question

Convert Json to Java object using reserved variables

Am having a JSON file as below

{
"boost_id": "75149",
"content_id": "627680",
"headline": "19 Rare Historical Photos That Will Leave You Breathless ",
"target_url": "http://stars.americancolumn.com/2016/02/21/historical-photos/?full=1",
"return": "district"
}


I need to convert json string to java object. Since the "return" is known as Java reserved keywords am unable to form a Dto with return variable.

Is there any other way to use the reserve variable and convert the above JSON to JAVA object.

Below is my Dto structure,

public class RevcontentReportResponse {

private String boost_id;
private String content_id;
private String headline;
private String target_url;
// private String return;

public String getBoost_id() {
return boost_id;
}

public void setBoost_id(String boost_id) {
this.boost_id = boost_id;
}

public String getContent_id() {
return content_id;
}

public void setContent_id(String content_id) {
this.content_id = content_id;
}

public String getHeadline() {
return headline;
}

public void setHeadline(String headline) {
this.headline = headline;
}

public String getTarget_url() {
return target_url;
}

public void setTarget_url(String target_url) {
this.target_url = target_url;
}
}


Main method:

ObjectMapper mapper = new ObjectMapper();

File json = new File("historic.json");
RevcontentReportResponse cricketer = mapper.readValue(json, RevcontentReportResponse.class);
System.out.println("Java object created from JSON String :");
System.out.println(cricketer);

Answer

Use the JsonProperty annotation:

@JsonProperty("return")
private String returnValue;

That said, JSON stands for JavaScript Object Notation, and return is also a JavaScript keyword (and it's the same for many other languages). You'd better change the name of the attribute in the JSON.