如何在Jackson框架Rest API中返回JSONArray的响应?

问题描述

@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();
}

我正在尝试像这样返回json数组,但是却收到这样的错误

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) 

任何人都可以帮助我将此序列化并提供响应。预先感谢。

解决方法

如果您正在使用spring,则不需要JSONArray,只需创建一个包含所有gettersetter的简单POJO类,然后使用ObjectMapper将JSON解析为该对象,然后编写POJO类以进行响应,如下所示:

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会自动转换为json,请检查此链接以了解更多info