前面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的应用的更多相关文章

  1. SpringMVC中使用Json传数据

    在web项目中使用Json进行数据的传输是非常常见且有用的,在这里介绍下在SpringMVC中使用Json传数据的一种方法,在我的使用中,主要包括下面四个部分(我个人喜好使用maven这类型工具进行项 ...

  2. springmvc 怎么响应json数据

    springmvc 怎么响应json数据@Controller@RequestMapping("/items") class ItemsController{  @RequestM ...

  3. springMVC参数绑定JSON类型的数据

    需求就是: 现在保存一个Student,并且保存Student的friend,一个student会有多个朋友,这里要传递到后台的参数是: var friends = new Array(); var ...

  4. SpringMVC中返回JSON时乱码的解决方案

    springMVC中返回JSON会出现乱码,解决如下: produces = "text/html;charset=UTF-8" @ResponseBody @RequestMap ...

  5. springmvc添加mock json的支持

    在springmvc中 添加对服务器classPath下的json文件解析之后返回的mock功能: import java.io.FileNotFoundException; import java. ...

  6. SpringMVC @RequestBody接收Json对象字符串 demo

    springmvc 的这个 @RequestBody 用得比较少,今天看了一下,还是很方便. @RequestBody 接收类似 [{name: "test"}, {name: & ...

  7. mongodb Decimal Spring data mongodb Decimal128 SpringMvc 序列化字符串 json converter

    Mongodb 3.4 就开始支持Decimal 类型,解决double的精度问题,但是不太好用,MapReduce的时候Array.sum 也不能计算 Decimal.比较坑,但是聚合可以用 Spr ...

  8. SpringMVC文件下载与JSON格式

    点击查看上一章 现在JSON这种数据格式是被使用的非常的广泛的,SpringMVC作为目前最受欢迎的框架,它对JSON这种数据格式提供了非常友好的支持,可以说是简单到爆. 在我们SpringMVC中只 ...

  9. SpringMVC中使用JSON

    前台发送: 传递JSON对象 function requestJson(){ $.ajax.({ type : "post", url : "${pageContext. ...

  10. 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. ...

随机推荐

  1. 高德面试:为什么Map不能插入null?

    在 Java 中,Map 是属于 java.util 包下的一个接口(interface),所以说"为什么 Map 不能插入 null?"这个问题本身问的不严谨.Map 部分类关系 ...

  2. C# .NET HttpWebRequest 显示指定SSL TLS 版本

    C# .NET HttpWebRequest 显示指定SSL TLS 版本 (TLS1.0,TLS1.1,TLS1.2) 在程序启动时加入这段代码: ServicePointManager.Secur ...

  3. 发现XWPFDocument写入Word文档时的小BUG:两天的探索与解决之旅

    引言 最近在使用XWPFDocument生成Word文档时,遇到一个错误:"未将对象引用设置到对象的实例".这个平常很容易找到原因的问题却困扰了我两天,最终发现问题出在设置段落时赋 ...

  4. 5分钟了解LangChain的路由链

    上上篇文章<5分钟理透LangChain的Chain>里用到了顺序链SequentialChain,它可以将多个链按顺序串起来.本文介绍LangChain里的另外1个重要的链:路由链. 1 ...

  5. CLR via C# 笔记 -- 枚举(15)

    1. 枚举继承System.Enum,后者继承 System.ValueType,所以枚举是值类型. 2. 枚举不能定义任何方法.属性和事件,不过可以定义扩展方法 3. ToString()方法 Co ...

  6. Java多线程生成波场靓号

    ​  玩区块链,手上没靓号怎么行.用网上的靓号生成器有一定的风险性,思来想去决定自己写一个.首先需要导入波场官方编辑 <!-- 引用本地Maven仓库--> <dependency& ...

  7. 采集modbus设备数据转wincc项目案例

    1         文档说明 1.   网关设置采集Modbus设备数据 2.   把采集的数据转成profinet协议转发给wincc. 2         VFBOX网关工作原理 VFBOX网关是 ...

  8. VScode连接服务器不用每次都输入密码

    VScode连接服务器不用每次都输入密码. 用git或xcode的ssh keygen生成一组不带密码的 rsa2048 的公钥id_rsa_nopasswd.pub和私钥id_rsa_nopassw ...

  9. 在C#中使用RabbitMQ做个简单的发送邮件小项目

    在C#中使用RabbitMQ做个简单的发送邮件小项目 前言 好久没有做项目了,这次做一个发送邮件的小项目.发邮件是一个比较耗时的操作,之前在我的个人博客里面回复评论和友链申请是会通过发送邮件来通知对方 ...

  10. NEEPU Sec 2023 Misc 两题题记

    GoingOn 题目描述 Keep going on channel 1 ;D 考察的是 midi lsb隐写 MIDI文件概述 CSV文件概述 midi转csv工具 midicsv 将 MIDI 文 ...