Spring引导REST Api JSON响应 - 没有为类org.json.JSONObject找到序列化程序

时间:2015-03-27 12:53:40

标签: java json spring spring-boot

我想构建一个RestAPI并返回一个JSONObject作为响应。 因此我创建了这个控制器:

    import java.util.List;
    import org.json.JSONArray;
    import org.json.JSONObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @RequestMapping("/api")
    public class ApiController {
        @Autowired
        private AssemblyRepository assemblyRepo;

        @RequestMapping(method=RequestMethod.POST)
        public ResponseEntity<JSONObject> sendResponse(@RequestBody AppRequest request) {

            //do some stuff with the data from requestBody

            List<Assembly> assemblys = assemblyRepo.findAll();
            JSONArray t_sub_objlist = new JSONArray();
            for (Assembly a: assemblys) {
                JSONObject object = new JSONObject();
                object.put("obj_type", a.getObjType());
                object.put("obj_key", a.getObjKey());
                t_sub_objlist.put(object);
            }
            response.put("t_sub_objlist", t_sub_objlist);
            return new ResponseEntity<JSONObject>(response, HttpStatus.OK);
        }
    }

当我将response打印到控制台时,一切看起来都不错:{"t_sub_objlist":[{"obj_key":"MS","obj_type":"NT"},{"obj_key":"MV","obj_type":"NT"}]}

但是当我想从外部访问API时,第一次重启服务器后,我收到此错误消息:

There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation

如果我再试一次,那么这条消息总会出现:

There was an unexpected error (type=Internal Server Error, status=500).
Could not write content: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ); nested exception is com.fasterxml.jackson.databind.JsonMappingException

我不知道我在这里做错了什么:)

0 个答案:

没有答案