SSM框架如何处理JSON格式数据和日期格式问题
一:返回json数据
方式1:
@ResponseBody
将标注该注解的处理方法的返回结果直接写入HTTP Response Body中(即返回字符串)
一般会在ajax异步获取数据时使用
@RequestMapping("/validUserCode")
@ResponseBody
public String userCodeIsExit(String userCode){
User user = userService.getUserByUserCode(userCode);
//Map<String, Object> map = new HashMap<>();
if(user != null){
return "{\"userCode\": \"exist\"}";
}else{
return "{\"userCode\": \"notexist\"}";
}
}
方式二:
2.1 下载jar包
使用JSON的jar包 fastjson-1.2.49.jar
可以自行去maven仓库中下载
2.2 代码层: 通过JSON.toJSONString() 这个方法转换为JSON格式
@RequestMapping("/RoleShow.do")
@ResponseBody
public String RoleShow(Model model){
List<Role> all=userMapperService.getRoles();
System.out.println("我到了");
if(all.size()>0){
return JSON.toJSONString(all);
}
return null;
}
二:解决JSON返回值中文乱码问题
解决方案1:
代码
<mvc:annotation-driven>
<mvc:message-converters>
<!--解决json返回中文乱码-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
三:JSON数据传递的日期格式问题
方法1:
vo类的日期属性上添加@JSONField(format= “yyyy-MM-dd”)
特点:该解决方案的代码具有强侵入性,紧耦合,并且修改麻烦,所以在实际开发,不建议采用这种硬编码的方式来处理*
@DateTimeFormat(pattern="yyyy-MM-dd")
@JSONField(format="yyyy-MM-dd")
private Date birthday; //出生日期
方法2:
配置FastJson的消息转换器-FastJsonHttpMessageConverter
设置features属性:指定输出时的日期转换器为WriteDateUseDateFormat
默认是yyyy-MM-dd HH:mm:ss格式,可通过@JSONField指定
<!--开启注解驱动,相当于配置了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter-->
<mvc:annotation-driven>
<mvc:message-converters>
<!--解决springmvc返回中文乱码-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!--解决数据格式问题: 1.把bean转换为json,2.处理日期格式-->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>