简体   繁体   中英

How to return response of JSONArray in Jackson framework rest api's?

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getData(@QueryParam("id") long id) throws Exception {
    JSONArray json = (getting some json data from db)
    ObjectMapper obj = new ObjectMapper();
    return Response.ok(obj.writeValueAsString(json)).build();
}

I am trying to return the json array like this but getting error like this.

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.json.JSONArray and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) 

Can anyone help me with serialize this and provide the response. Thanks in Advance.

If you are using spring then you don't need JSONArray , just create a simple POJO class with all the getter and setter and use ObjectMapper to parse the JSON into that object, and then write the POJO class to response, as given below:

public ResponseEntity<DummyObject> getData(@QueryParam("id") long id) throws Exception 
    DummyPojo obj = mapper.readValue(json, DummyPojo.classs);
    return ResponseEntity.ok(obj)
}

// Replace DummyObject with your class

Spring will automatically converts into json, please check this link for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM