Pergunta

in spring 3 controller

@RequestMapping(value = "/employee/{id}", RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable long empID) {
    Employee employee = employeeService.getByID(empID);
    return employee;
}

which file should i modify, so that the json would return like below

instead of returning "['foo', 'bar']"

return this "/*['foo', 'bar']*/" (with comment) ?

Foi útil?

Solução

Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.

So, you can provide your own HttpMessageConverter implementation by overriding

protected void writeInternal(Object o,
                         HttpOutputMessage outputMessage)
                  throws IOException,
                         HttpMessageNotWritableException

method of MappingJacksonHttpMessageConverter, which could server the purpose.

Outras dicas

Quick note regarding comments: comments are not (alas!) part of JSON specification, so using them means using non-standard JSON.

For what it's worth, it is possible to make some JSON parsers (including Jackson) handle comments (for Jackson, see http://wiki.fasterxml.com/JacksonFeaturesParser); as well as write them (need to use 'JsonGenerator.writeRaw("/.../")').

But maybe Spring has a way to decorate response, as that would probably be simpler to implement.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top