【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. ...
随机推荐
- vue移动端 滚动
better-scroll: https://better-scroll.github.io/docs/zh-CN/guide/ 影院列表数据使用better-scroll来完成数据的展示,此插件对于 ...
- EF MYSQL 出现:输入字符串的格式不正确
实体类字段和数据库类型不一致. 比如:数据库是char类型字段,程序里声明为int.
- RAS非对称加解密-RAS加解密和签名和验签,密钥生成器(java代码)
RAS非对称加解密-RAS加解密和签名和验签,密钥生成器(java代码)RSA 算法是一种非对称加解密算法.服务方生成一对 RSA 密钥,即公钥 + 私钥,将公钥提供给调用方,调用方使用公钥对数据进行 ...
- logback日志格式模板,基于TraceId搜索完整的请求链路日志
logback日志格式模板,基于TraceId搜索完整的请求链路日志 日志打印格式:(可以基于TraceId:4d484c2a110eae9d来搜索完整的请求链路日志2023-08-28 15:06: ...
- MySQL查询关于区分字母大小写问题
前段时间在工作中测试提出了一个BUG,让我把根据ID查询区分大小写的功能去掉,大小写都随便查,然后我在SQL的位置加上了UPPER(id) = UPPER(#{id})的写法,而同事知道这个问题后的反 ...
- python Django项目以Debug模式启动和外网访问启动
一.Django介绍 介绍: 完善的web框架,包括前端和后端的管理,django项目管理: 管理后台访问:后面补充 前端页面访问:根据app/settings.py文件下配置的访问地址 1.1 项目 ...
- bugly进阶01-集成bugly时的相关参数
bugly进阶01-集成bugly时的相关参数 个人github CSDN博客 前言 bugly的集成十分的简单,在代码中只需要简单的一个语句就可以轻松集成: - (BOOL)application: ...
- 从 Dict 转到 Dataclass
从 dataclass 转到 dict 可以用 asdict 函数 , 反向转换的时候 就比较困难. 不用外部的包的情况下, 提供一种思路. def mask(v, d): #v 是 dict 数据, ...
- 静态 top tree 入门
理论 我们需要一个数据结构维护树上的问题,仿照序列上的问题,我们需要一个方法快速的刻画出信息. 比如说线段树就通过分治的方式来通过将一个区间划分成 \(\log n\) 个区间并刻画出这 \(\log ...
- Java常见的加密方式
前言 传说在古罗马时代,发生了一次大战.正当敌方部队向罗马城推进时,古罗马皇帝凯撒向前线司令官发出了一封密信:VWRS WUDIILF.这封密信被敌方情报人员翻遍英文字典,也查不出这两个词的意思. 此 ...