JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,目前使用较为广泛。
JSON 使用完全独立与编程语言的文本格式来存储和表示数据。
有较高的阅读性,易于机器解析和生成,有效的提高网络数据传输的效率。
对象表示为键值对,数据由逗号隔开。
花括号保存对象。
方括号保存数组。
{"name":"zyh"}
{"age":"18"}
{"sex":"man"}
JSON是JavaScript对象的字符串表示法,它使用字符串文本表示一个JS对象。
/*JS对象*/
var user = {
id: 1,
name: "hang",
sex: "男"
};
/*JSON字符串*/
var json = `{"id":"1","name":"zyh","sex":"男"}`
JSON 字符串和JavaScript的转换
JSON转JS对象:JSON.parse()方法
JS对象转JSON:JSON.stringify()方法
//将JSON字符串转换为JS对象
let xiaochen = JSON.parse('{"id":"112","name":"xiaochen","sex":"女"}');
//将JS对象转换为JSON字符串
let xiaoli = JSON.stringify({id:113,name:"xiaoli",sex:"男"});
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.10.0version>
dependency>
搭建测试环境:
package com.zyh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private String name;
private int age;
private String sex;
}
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>SpringMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>SpringMVCservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/url-pattern>
filter-mapping>
web-app>
<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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.zyh.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
编写Controller
package com.zyh.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping(value = "/t1")
// @ResponseBody //不会再经过视图解析器的拼接,而是直接返回一个字符串
public String test1() {
ObjectMapper objectMapper = new ObjectMapper();
User user = new User("小陈", 18, "女");
String str = null;
try {
str = objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return str;
}
}
我们发现数据被显示在前端页面上,但确实乱码的。
方式1、 直接在@RequestMapping(value = "/t1")
指定响应返回体和编码
@RequestMapping(value = "/t1",produces = "application/json;charset=utf-8")
方式2、 在Spring配置文件中统一处理
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<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>
@RequestMapping("/t2")
public String test2() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
List<User> userList = new ArrayList<User>();
User user1 = new User("小王1",19,"男");
User user2 = new User("小王2",20,"男");
User user3 = new User("小王3",21,"男");
User user4 = new User("小王4",22,"男");
User user5 = new User("小王5",23,"男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
String str = objectMapper.writeValueAsString(userList);
return str;
}
@RequestMapping("/t3")
public String test3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
String format = dateFormat.format(new Date());
return mapper.writeValueAsString(format);
}
@RequestMapping("/t3")
public String test3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
mapper.setDateFormat(dateFormat);
return mapper.writeValueAsString(new Date());
}
package com.zyh.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JsonUtils {
public static String getJson(Object object, String dateFormat) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
mapper.setDateFormat(format);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static String getJson(Object object) {
return getJson(object,"YYYY-MM-dd HH:mm:ss");
}
}
使用工具类传递JSON: 不用每次去创建ObjectMapper对象,直接使用工具类即可。
package com.zyh.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.pojo.User;
import com.zyh.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
public class UserController {
@RequestMapping(value = "/t1")
// @ResponseBody //不会再经过视图解析器的拼接,而是直接返回一个字符串
public String test1() throws JsonProcessingException {
User user = new User("小陈", 18, "女");
return JsonUtils.getJson(user);
}
@RequestMapping("/t2")
public String test2() throws JsonProcessingException {
List<User> userList = new ArrayList<User>();
User user1 = new User("小王1", 19, "男");
User user2 = new User("小王2", 20, "男");
User user3 = new User("小王3", 21, "男");
User user4 = new User("小王4", 22, "男");
User user5 = new User("小王5", 23, "男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
return JsonUtils.getJson(userList);
}
@RequestMapping("/t3")
public String test3() throws JsonProcessingException {
return JsonUtils.getJson(new Date());
}
}
FastJson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。
步骤:
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.62version>
dependency>
package com.zyh.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.pojo.User;
import com.zyh.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
public class UserController {
//使用JSON
@RequestMapping("/t4")
public String test4() {
List<User> users = new ArrayList<User>();
User user1 = new User("小王1", 19, "男");
User user2 = new User("小王2", 20, "男");
User user3 = new User("小王3", 21, "男");
User user4 = new User("小王4", 22, "男");
User user5 = new User("小王5", 23, "男");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
System.out.println("--------------Java对象转JSON字符串------------");
String str = JSON.toJSONString(users);
System.out.println(str);
System.out.println("--------------JSON字符串转Java对象------------");
List list = JSON.parseObject(str, List.class);
System.out.println(list);
System.out.println("--------------Java对象转JSON对象------------");
JSONObject json = (JSONObject) JSON.toJSON(user1);
System.out.println(json);
System.out.println("--------------Java对象转JSON字符串------------");
User user = JSON.toJavaObject(json, User.class);
System.out.println(user);
return str;
}
}
JSON完结