Spring MVC:解析JSON文档时出错

史提芬

我有一个用于REST通信的spring-MVC。这是控制器:

@RestController
@RequestMapping("/db")
public class RestController {

    @Inject
    private EmpRepositoryImpl empRepository;


    @RequestMapping(value = "/{tableName}.json", method = RequestMethod.GET, produces = "application/json")
    public String getTableRecords(  @PathVariable String tableName){

        List<Map<String, Object>> resultList = empRepository.getAllEmpRecords(tableName);

        return resultList.toString();
    }

}

我在Firefox中得到的结果是:

There was an error parsing the JSON document. The document may not be well-formed.
expected property name or '}' at line 1 column 3
[{nodeID=0, neo_eb_id=11, neo_eb_bossID=11, neo_eb_name='Smith'}, {nodeID=1, neo_eb_id=12, neo_eb_bossID=11, neo_eb_name='Johnson'}, {nodeID=2, neo_eb_id=13, neo_eb_bossID=11, neo_eb_name='Roberts'}, {nodeID=3, neo_eb_id=14, neo_eb_bossID=13, neo_eb_name='Doe'}]
  1. spring生成的JSON格式似乎有什么问题?

  2. 如何在JSON中显示此结果,而JSON在我用firefox打开的其他json中发生时,可以以缩进和填充的方式突出显示在eyecandy语法中?

马可·艾格

更改为

@RestController
@RequestMapping("/db")
public class RestController {

    @Inject
    private EmpRepositoryImpl empRepository;


    @RequestMapping(value = "/{tableName}.json", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public List<Map<String, Object>> getTableRecords(  @PathVariable String tableName){
        return empRepository.getAllEmpRecords(tableName);
    }
}

假设您使用的是spring 3.2.x,spring会自动注册MappingJackson2HttpMessageConverter,它能够将处理程序方法返回的值转换为有效的JSON。application/json除非Jackson不在类路径中(除非您必须手动将Jackson添加到类路径中),否则此转换器将支持并在春季之前自动创建和注册。只要您没有任何高级要求,Spring的默认Jackson配置就足够了并且可以完美地工作。

另外,通过使用这种方法(@ResponseBody并返回模型本身,而不是特定的表示形式),您可以基于例如Accept报头使用不同的转换器(例如,对于XML),而不必更改控制器。您只需要在Spring配置中添加其他转换器即可。

这种方法的一个非常重要的好处是....您拥有可测试的代码!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章