Springmvc返回json的配置和对数据中值为null的处理方法:
先在springmvc的配置文件中添加Json转换器
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
有些特殊情况,我们不能将null字段直接去除,而是需要给予一个默认的值空字符串,则可以编写一个专门处理的方法:
public JSONObject ajaxGrid( Map<String, Object> dataMap) {
ObjectMapper objectMapper = new ObjectMappr();
//com.fasterxml.jackson.databind.ObjectMapper;
JSONObject json = null;
try {
jsonString = objectMapper.writeValueAsString(dataMap);
jsonString = jsonString.replaceAll("null", "\"\"");
json = JSONObject.fromObject(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}