My model looks like below, where in bookJson is a json object -
{
"name" : "somebook",
"author" : "someauthor"
}
public class Book{
private int id;
private JSONObject bookJson;
public int getId(){return this.id;}
public JSONObject getBookJson(){this.bookJson;}
public void setId(int id){this.id = id;}
public void setBookJson(JSONObject json){this.bookJson = json;}
}
JSONObject belongs to org.json package
When My RestController returns Book object in a ResponseEntity object , I get the error -
"errorDesc": "Type definition error: [simple type, class org.json.JSONObject]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
What is the best way to achieve this?
Can we not achieve this without having to have a model class with all fields of bookJson?
Figured this out.
Added JSONObject as a Map instead and used ObjectMapper to do all the conversions.
public class Book{
private int id;
private Map<String, Object>bookJson;
public int getId(){return this.id;}
public Map<String, Object>getBookJson(){this.bookJson;}
public void setId(int id){this.id = id;}
public void setBookJson(Map<String, Object> json){this.bookJson = json;}
}
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
} catch (IOException e) {
throw new JsonParsingException(e.getMessage(), e);
}