Spring Controller生成的无效JSON内容(使用Jackson库)

时间:2013-03-11 12:58:10

标签: java json spring spring-mvc jackson

由于某些我不知道的原因,当向我的Spring控制器发出请求时,它返回一个无效的JSON值。我正在使用Jackson来映射我的JSON对象。这是我发出请求时返回的数据:

{} && 
{
    "registros": [
        {
            "id": 251,
            "matricula": "32849923",
            "dadoPessoal": {
                "nome": "Testando",
                "email": "tiare@terra.com.br",
                "telefone": "1235324812",
                "celular": "123832911",
                "foto": null,
                "salario": 3829
            },
            "status": true,
            "nascimento": {
                "dataNascimento": 1417485600000,
                "nascionalidade": "Brasil",
                "localNascimento": "SP"
            },
            "documentoPessoal": {
                "rg": "8329892332",
                "orgaoEmissor": "SSP/SP",
                "dataEmissao": 1417485600000,
                "cpf": "016.015.XXX-XX",
                "tituloEleitor": "adw91021",
                "zonaDeVoto": "91aa",
                "sessaoVoto": "2a",
                "enderecoVoto": "adw"
            },
            "dataAdmissao": 1361674800000,
            "dataDesligamento": null,
            "version": 0
        }
    ],
    "total": 1
}

这里的问题是某些无效字符“{}&&”正被添加到JSON的开头。我不明白的是怎么样?它添加了我在Spring方法中没有定义的值。

我的请求映射:

@Override
@RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView view = new ModelAndView(VIEW_INDEX);

    view.addObject("registros", service.findAll());
    view.addObject("total", service.findAll().size());
    return view;
}

杰克逊配置:

/**
 * @return MappingJacksonJsonView
 */
@Bean
public MappingJacksonJsonView mappingJacksonJsonView() {
    MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView();
    mappingJacksonJsonView.setContentType("application/json");
    mappingJacksonJsonView.setObjectMapper(this.objectMapper());
    mappingJacksonJsonView.setEncoding(JsonEncoding.UTF8);
    mappingJacksonJsonView.setPrefixJson(true);
    return mappingJacksonJsonView;
}

/**
 * @return ContentNegotiatingViewResolver
 */
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
    List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();

    // Tiles
    viewResolvers.add(this.tileViewResolver());

    // Views 
    List<View> defaultViews = new ArrayList<View>();
    defaultViews.add(this.mappingJacksonJsonView());

    ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();

    contentNegotiatingViewResolver.setViewResolvers(viewResolvers);
    contentNegotiatingViewResolver.setDefaultViews(defaultViews);
    contentNegotiatingViewResolver.setOrder(0);

    return contentNegotiatingViewResolver;
}

1 个答案:

答案 0 :(得分:3)

谢谢大家。我发现了错误!! 当我开始阅读javadoc时,我发现了这个:

“指示此视图的JSON输出是否应以”{}&amp;&amp; “。默认是假的。”

springsource docs