我正在构建一个简单的Spring MVC webapp并正在开发jetty。我的控制器绑定使用了这个:
@RequestMapping(value = RESTRoutes.CREATE_DOC, method = RequestMethod.POST)
public @ResponseBody String getDoc
从JSONObject返回一个String,在我的ajax响应中正确地解析为JSON。
但是使用那些相同的控制器,我将我的gradle war部署到了tomcat,我的json回来后被包裹为真正的字符串。
所以我改变了标题以使用Map,这似乎解决了jetty和tomcat中的问题:
@RequestMapping(value = RESTRoutes.CREATE_DOC, method = RequestMethod.POST)
public @ResponseBody Map<String, String> getDoc
我将字符串转换为地图:
HashMap<String, String> jsonResponse = new HashMap<String, String>();
if(claimFolder.has("error")){
response.setStatus(500);
}else{
jsonResponse = new ObjectMapper().readValue(claimFolder.toString(), HashMap.class);
}
return jsonResponse;
我的问题是为什么这是必须的?
这是我的杰克逊转换器配置:
<bean id="formConverter" class="org.springframework.http.converter.FormHttpMessageConverter" />
<!-- add byte[] converter -->
<bean id="byteArrayConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<property name="supportedMediaTypes" value="application/octet-stream" />
</bean>
<!-- add in our JSON message converter -->
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json;charset=UTF-8" />
</bean>
<!-- add in our plain string message converter -->
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
<!-- Expose the authenticated handler to all beans that have been declared via annotation -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
TL; DR:为什么jetty和tomcat以不同的方式返回字符串化的JSON?
答案 0 :(得分:1)
嗯,Spring内容协商将String对象转换为简单字符串而不将其编组为JSON对象是绝对正常的。为了在JSON对象中序列化java String对象,您需要先将其包装在某个java类中。例如:
QuestionStatus {
private String status;
public QuestionStatus(String status) {
this.status = status;
}
public getStatus() {
return status;
}
}
因此,你必须在Controller
方法中返回而不是String,而不是QuestionStatus。