【SpringMVC】09 对JSON的应用
前面JavaWeb的JSON回顾:
https://www.cnblogs.com/mindzone/p/12820877.html
上面的这个帖子我都还没有实际写进Servlet使用,要Mark一下了
我们配置一个演示的Bean
package cn.dai.pojo; import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; /**
* @author ArkD42
* @file SpringMVC
* @create 2020 - 05 - 07 - 15:06
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private Integer age;
private Boolean gender;
}
编写控制器
@Controller
public class JsonController { @GetMapping("/json01")
public String json01(Model model){ Person person = new Person("阿强", 22, true); model.addAttribute("msg",person.toString()); return "test";
}
}
测试我们的响应结果是否会乱码
然后导入Maven坐标
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
使用Jackson
package cn.dai.controller; import cn.dai.pojo.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import java.util.Arrays; /**
* @author ArkD42
* @file SpringMVC
* @create 2020 - 05 - 07 - 15:06
*/
@Controller
public class JsonController { @GetMapping("/json01")
public String json01(Model model) throws JsonProcessingException { Person person = new Person("阿强", 22, true); ObjectMapper objectMapper = new ObjectMapper(); String s = objectMapper.writeValueAsString(person); model.addAttribute("msg", Arrays.toString(new String[]{s,"\n",person.toString()})); return "test";
}
}
访问测试
注意要记得再Web包里面导入Jackson的依赖,
不然会出现找不到Bean异常
测试单个的JSON返回
也是没有问题的,不过这样我也就没有办法演示JSON乱码的问题了
针对JSON乱码的问题,可以使用一个Produces属性
是@RequestMapping注解中的属性
或者使用SpringMVC原生xml配置
Bean方式配置,如果无效,可以尝试放在注解驱动的外面
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
"
>
<!-- 目录扫描的方式注册Bean -->
<context:component-scan base-package="cn.dai.controller" />
<!-- 默认的Servlet处理器 不处理静态资源-->
<mvc:default-servlet-handler />
<!-- MVC 注解驱动支持-->
<mvc:annotation-driven> <!-- 解决JSON乱码 -->
<mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false" />
</bean>
</property>
</bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean> </beans>
对时间的JSON转换,这是使用LocalDateTime的API
@GetMapping("/json02")
public String json02(Model model) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); LocalDateTime now = LocalDateTime.now();
System.out.println(now); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); String format = dateTimeFormatter.format(now); String nows = objectMapper.writeValueAsString(now); objectMapper.writeValueAsString(format); model.addAttribute("msg", "时间转换测试");
model.addAttribute("now", now);
model.addAttribute("nows", nows);
model.addAttribute("format", format); /*
时间转换测试
2020-05-07T16:03:07.177
{"month":"MAY","year":2020,"dayOfYear":128,"dayOfMonth":7,"hour":16,"minute":3,"monthValue":5,"nano":177000000,"second":7,"dayOfWeek":"THURSDAY","chronology":{"id":"ISO","calendarType":"iso8601"}}
2020-5-7
*/ return "time";
}
然后是原生Date & SimpleDateFormat
@GetMapping("/json03")
public String json03(Model model) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat.format(date); objectMapper.writeValueAsString(format); return "time";
}
Fastjson
Maven坐标
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
@GetMapping("/json04")
public String json04(Model model) { String s = JSON.toJSONString(new Date()); model.addAttribute("msg", s);
return "time";
}
【SpringMVC】09 对JSON的应用的更多相关文章
- SpringMVC中使用Json传数据
在web项目中使用Json进行数据的传输是非常常见且有用的,在这里介绍下在SpringMVC中使用Json传数据的一种方法,在我的使用中,主要包括下面四个部分(我个人喜好使用maven这类型工具进行项 ...
- springmvc 怎么响应json数据
springmvc 怎么响应json数据@Controller@RequestMapping("/items") class ItemsController{ @RequestM ...
- springMVC参数绑定JSON类型的数据
需求就是: 现在保存一个Student,并且保存Student的friend,一个student会有多个朋友,这里要传递到后台的参数是: var friends = new Array(); var ...
- SpringMVC中返回JSON时乱码的解决方案
springMVC中返回JSON会出现乱码,解决如下: produces = "text/html;charset=UTF-8" @ResponseBody @RequestMap ...
- springmvc添加mock json的支持
在springmvc中 添加对服务器classPath下的json文件解析之后返回的mock功能: import java.io.FileNotFoundException; import java. ...
- SpringMVC @RequestBody接收Json对象字符串 demo
springmvc 的这个 @RequestBody 用得比较少,今天看了一下,还是很方便. @RequestBody 接收类似 [{name: "test"}, {name: & ...
- mongodb Decimal Spring data mongodb Decimal128 SpringMvc 序列化字符串 json converter
Mongodb 3.4 就开始支持Decimal 类型,解决double的精度问题,但是不太好用,MapReduce的时候Array.sum 也不能计算 Decimal.比较坑,但是聚合可以用 Spr ...
- SpringMVC文件下载与JSON格式
点击查看上一章 现在JSON这种数据格式是被使用的非常的广泛的,SpringMVC作为目前最受欢迎的框架,它对JSON这种数据格式提供了非常友好的支持,可以说是简单到爆. 在我们SpringMVC中只 ...
- SpringMVC中使用JSON
前台发送: 传递JSON对象 function requestJson(){ $.ajax.({ type : "post", url : "${pageContext. ...
- SpringMVC整合FastJson:用"最快的json转换工具"替换SpringMVC的默认json转换
2017年11月23日 09:18:03 阅读数:306 一.环境说明 Windows 10 1709 Spring 4.3.12.RELEASE FastJson 1.2.40 IDEA 2017. ...
随机推荐
- IDEA的安装、激活(到25年2月)&汉化
1,在官网下载IDEA软件,官网 2,下载之后,双击安装包,然后一直点击next即可. (中间可以按照自己的要求设置安装目录) 3,快捷方式和java打钩 4,点击install即可进行安装,时间有一 ...
- mysql中,时间类型datetime和timestamp的区别
TIMESTAMP和DATETIME的相同点: 两者都可用来表示 YYYY-MM-DD HH:MM:SS 类型的日期. TIMESTAMP和DATETIME的不同点: 1> 两者的存储方式不一 ...
- INFINI Labs 产品更新 | Easysearch 新增快照搜索功能,Console 支持 OpenSearch 存储
INFINI Labs 产品又更新啦~,包括 Easysearch v1.7.0.Console v1.13.0.本次各产品更新了 Easysearch 快照搜索功能:Console 支持 OpenS ...
- C#.NET Rsa私钥加密公钥解密
在C#中,RSA私钥只能签名,不能加密,如果要加密,要借助BouncyCastle库. nuget 中引用 Portable.BouncyCastle. 工具类: RsaEncryptUtil usi ...
- 如果你也用过 struts2.简单介绍下 springMVC 和 struts2 的区别有哪些?
a.springmvc 的入口是一个 servlet 即前端控制器,而 struts2 入口是一个 filter 过虑器. b.springmvc 是基于方法开发(一个 url 对应一个方法),请求参 ...
- 2. Elasticsearch 使用插件和kibana操作
引言 在上一篇文章中1. Elasticsearch 入门安装与部署 已经教了大家如何在linux系统中安装和启动Elasticsearch,本文就带大家一起学习如何操作 Elasticsearch. ...
- 未能加载文件或程序集“netstandard,Version=2.0.0.0, Culture=neutral,PublicKeyToken=cc7b13ffcd2ddd51”或它的某一个依赖项 解决
未能加载文件或程序集"netstandard,Version=2.0.0.0, Culture=neutral,PublicKeyToken=cc7b13ffcd2ddd51"或它 ...
- 高通Android平台 电池 相关配置
背景 在新基线上移植有关的代码时,在log中发现有关的东西,请教了有关的同事以后,解决了这个问题. [ 12.775863] pmi632_charger: smblib_eval_chg_termi ...
- 说说你对 SPA 单页面的理解,它的优缺点分别是什么?
SPA( single-page application )仅在 Web 页面初始化时加载相应的 HTML.JavaScript 和 CSS. 一旦页> 面加载完成,SPA 不会因为用户的操作而 ...
- Mac Docker设置国内镜像加速器
安装docker 点我直达 设置国内加速镜像 { "experimental": false, "features": { "buildkit&quo ...