Andrea Borzi Andrea Borzi - 1 month ago 22
reST (reStructuredText) Question

Cannot deserialize JSONObject (inside of JSONArray) in Java Spring

So, I have this method here:

@RequestMapping(value = "/getFields", produces = "application/json")
public Response getFields(@RequestParam(value = "id") int id)


and I have a class which extends Response.
In this class, I have defined a
JSONArray
, in which I put a
JSONObject
through a method which wraps
JSONArray.put(JSONObject obj)
.

At the end of my getRegistrationFields I return the instantiated object of the class extending Response.

This way, Spring should return the JSONArray contained in this object, and I should see it when I call "/getFields" REST method.

However, it gives me an Error 500

Could not write content: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer


Is there a quick way to fix this?

Answer

Try to use the next dependency (or jar:

<dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>${jackson.version}</version>
</dependency>

If doesn't help, try to use Jackson ArrayNode and ObjectNode instead of JSONArray and JSONObject.

   ObjectMapper mapper = new ObjectMapper();
    ArrayNode arrayNode = mapper.createArrayNode();
    Object obj = new Object();
    arrayNode.addPOJO(obj);
    arrayNode.add(mapper.createObjectNode().put("field1", "Hello Stack!"));

Please see the link to the doc: http://fasterxml.github.io/jackson-databind/javadoc/2.0.0/com/fasterxml/jackson/databind/node/ArrayNode.html

Comments