2016-12-14 58 views
0

我有一个基本的休息控制器返回模型列表中JSON到客户端:爪哇 - 弹簧复位JSON对象/数组

@RestController 
public class DataControllerREST { 

    @Autowired 
    private DataService dataService; 

    @GetMapping("/data") 
    public List<Data> getData() { 
     return dataService.list(); 
    } 

} 

在这种格式返回数据:

[ 

    { 
     "id": 1, 
     "name": "data 1", 
     "description": "description 1", 
     "active": true, 
     "img": "path/to/img" 
    }, 
    // etc ... 

] 

那是伟大的开始,但我想过这个返回格式的数据:

[ 
    "success": true, 
    "count": 12, 
    "data": [ 
     { 
      "id": 1, 
      "name": "data 1", 
      "description": "description 1", 
      "active": true, 
      "img": "path/to/img" 
     }, 
     { 
      "id": 2, 
      "name": "data 2", 
      "description": "description 2", 
      "active": true, 
      "img": "path/to/img" 
     }, 
    ] 
    // etc ... 

] 

,但我不能确定回合这个问题,因为我不能返回任何类作为JSON ...任何人有建议或意见?

问候和感谢!

+0

当你的JSON以“[”开头,这意味着它的数组。你实际上是指一个数组还是你的意思是一个有'data'数组的对象('{}')? – Adam

回答

4

“因为我不能返回任何类作为JSON” - 说谁?

其实这正是你应该做的。在这种情况下,您将需要创建一个包含所有您想要的字段的外部类。这将是这个样子:

public class DataResponse { 

    private Boolean success; 
    private Integer count; 
    private List<Data> data; 

    <relevant getters and setters> 
} 

而且你的服务代码将变为像这样:

@GetMapping("/data") 
public DataResponse getData() { 
    List<Data> results = dataService.list(); 
    DataResponse response = new DataResponse(); 
    response.setSuccess(true); 
    response.setCount(results.size()); 
    response.setData(results); 
    return response; 
} 
+0

嘿,谢谢你的回答, 我正在抱怨的“转换器”: “org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是java.lang.IllegalArgumentException:找不到转换器的返回值键入:class com.example.app.rest.controller.DataResponse“ 你有什么建议吗? –

+0

您是否为DataResponse添加了相关的getter和setter?是[杰克逊包括作为您的项目的一部分](http://stackoverflow.com/questions/32905917/how-to-return-json-data-from-spring-controller-using-responsebody)? – rmlan

+0

你是男人 忘了那些getter' ... –