springmvc对于JSON对象的处理

时间:2023-03-09 07:22:38
springmvc对于JSON对象的处理

1、常见的json    jar包,及其优缺点(开发中可以一起使用)

  json-lib           缺点:依赖第三方的包
  jackson        SpringMVC内置的json装换工具,依赖包较少
  GSON          谷歌开源jar包,功能最强大,不依赖任何包
  fastjson        阿里巴巴开源jar包,效率最高,不依赖任何报

2、在需要返回的方法前面加上     @ResponseBody注解

 @RequestMapping(value = "/user/userview.html", method = RequestMethod.POST)
@ResponseBody
public Object getUserById(@RequestParam String uid) {
String cjson = "";
if (StringUtils.isNullOrEmpty(uid)) {
return "nodata";
} else {
try {
User user = userService.getUserById(uid);
cjson = JSON.toJSONString(user);
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
}
return cjson;
}

3、对日期格式的处理

springmvc对于JSON对象的处理

[{"address":"北京海淀","age":5,"birthday":,"createdBy":0,"gender":2,"id":19,"modifyBy":0,"phone":"13878907654","userCode":"admin","userName":"系统管理员","userType":1}]

在查看日期格式的内容时,我们发现日期格式不是我们想要的

 解决办法1:

在对应实体类的日期加上注解:针对阿里巴巴的  fastjson---------------@JSONField(format="yyyy-MM-dd"),缺点是依赖性太强,强耦合

springmvc对于JSON对象的处理

解决方法2:

配置视图解析图

在springMVC配置文件中配置 

 <!-- 配置多视图解析器,允许用同样的内容数据来呈现不同的view -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<!-- 支持参数匹配 -->
<property name="favorParameter" value="true"/>
<!-- contentType 以何种格式进行展示 -->
<property name="mediaTypes">
<map>
<entry key="html" value="text/html;charset=UTF-8"/>
<entry key="xml" value="application/xml;charset=UTF-8"/>
<entry key="json" value="application/json;charset=UTF-8"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
@RequestMapping(value = "/user/userview2", method = RequestMethod.GET)
@ResponseBody
public Object getUserById2(@RequestParam String uid) {
User user = new User();
try {
user = userService.getUserById(uid);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}

访问路径:两种方式:(可以访问json、xml、html、xls....)

(1)、使用扩展名:   http://localhost:8080/ShopSystem/user/userview2.json?uid=19

(2)、使用参数(favorParameter):   http://localhost:8080/ShopSystem/user/userview2?uid=19&format=json

注:访问xml时需要在对应实体类配置注解       @XmlRootElement

springmvc对于JSON对象的处理

页面输出:

springmvc对于JSON对象的处理