SPingMVC return JSON

zhangyao 2014-10-24
mvc配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
<value>*/*;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>

后台代码:
@RequestMapping (value = "/doLogin",method = RequestMethod.POST)
@ResponseBody
public  JSON doLogin(HttpServletRequest request,Model model){
logger.debug("验证登录提交信息  doLogin..........");
String loginname = request.getParameter("loginname");
String password = request.getParameter("password");
logger.debug("loginname : "+loginname+" password : "+password);
try {
User user = userService.getUserByLoginName(loginname);
if(EmptyUtil.isEmpty(user)){
logger.debug(JsonResult.failureToJson("用户名不存在,请确认!").toString());
return JsonResult.failureToJson("用户名不存在,请确认!");
}else{
String passwordMd5 = StringUtil.md5Hex(password);
logger.debug("passwordMd5 : "+passwordMd5);
if(user.getPassword().equals(passwordMd5)){
this.setSystemSession(request, user);
logger.debug(JsonResult.successToJson("用户验证成功!").toString());
return JsonResult.successToJson("用户验证成功!");
}else{
logger.debug(JsonResult.failureToJson("用户密码不正确,请确认!").toString());
return JsonResult.failureToJson("用户密码不正确,请确认!");
}
}
} catch (Exception e) {
e.printStackTrace();
JSON json = JsonResult.failureToJson("系统错误,请联系管理员!");
logger.debug("json.toString() : "+json.toString());
return json ;
}
}

报错:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Object is null (through reference chain: net.sf.json.JSONObject["jsonConfig"]->net.sf.json.JSONNull["empty"]); nested exception is org.codehaus.jackson.map.JsonMappingException: Object is null (through reference chain: net.sf.json.JSONObject["jsonConfig"]->net.sf.json.JSONNull["empty"])

如果我将return JSON 改为 return String,然后将JSON.toString就没问题。

请问大神们为什么?
静夜独窗 2014-10-31
@ResponseBody会自动把String类型的json数据转成json到页面。如果你要return JSON,就把@ResponseBody去掉,应该就可以了
Global site tag (gtag.js) - Google Analytics