什么是JSON?
- JSON(JavaScript Object Notation,JS对象标记)是一种轻量级数据交换格式,目前使用特别广泛。
- 采用完全独立于编程语言的文本格式来存储和表示数据。
- 简洁和清晰的层次结构使得JSON成为理想的数据交换语言。
- 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
在JavaScript语言中,一切都是对象,任何JavaScript支持的类型都可以通过JSON来表示,例如字符串、数字、对象、数组等。JSON的要求与语法格式为:
- 对象标识为键值对,数据由逗号分隔。
- 花括号保存对象
- 方括号保存数组
JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号""包裹,使用冒号:分隔,然后紧接着值:
{"name" : "stitch"}
{"age" : "18"}
{"sex" : "男"}
JSON是JavaScript对象的字符串表示法,它使用文本表示一个JS对象的信息,本质是一个字符串。
var obj = {a : "hello", b : "world"}; // 这是一个对象,键名也是可以使用""包裹的
var json = '{"a" : "hello", "b" : "world"}'; // 这是一个JSON字符串
JSON和JavaScript对象互转
- 要实现从JSON字符串转化为JavaScript对象,使用JSON.parse()方法
var obj = JSON.parse('{ "a" : "hello", "b" : "world"}');
// 结果是{ a : "hello", b : "world"}
要实现从JavaScript对象转为JSON字符串,使用JSON.stringify()方法
var json = JSON.stringify({ a : "hello", b : "world"});
// 结果是 '{ "a" : "hello", "b" : "world"}'
Controller返回JOSN数据
- 导包jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
- 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--1、注册DispatchServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】- servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求:(不包括.jsp)-->
<!--/* 匹配所有的请求:(包括*.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
</web-app>
- 创建User实体类(导入lombok)
package indi.stitch.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
- 创建UserController
@Reponsebody(不走视图解析器,返回字符串)
package indi.stitch.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import indi.stitch.pojo.User;
import indi.stitch.utils.JSONUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
//@RestController
public class UserController {
@RequestMapping("j1")
@ResponseBody
public String json1() throws JsonProcessingException {
User user = new User("张三", 18, "男");
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(user);
return str;
}
@RequestMapping("j2")
public String json2() throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
List<User> users = new ArrayList<User>();
User user1 = new User("张三", 18, "男");
User user2 = new User("李四", 18, "男");
User user3 = new User("王五", 18, "男");
User user4 = new User("赵六", 18, "男");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
return mapper.writeValueAsString(users);
}
@RequestMapping("j3")
public String json3() throws JsonProcessingException{
Date date = new Date();
String json = JSONUtils.getJson(date, "yyyy-MM-ss HH:mm:ss");
return json;
}
}
- 使用jackson的ObjectMapper.writeValueAsString将Java对象转为JSON字符串
@RequestMapping("j1")
@ResponseBody
public String json1() throws JsonProcessingException {
User user = new User("张三", 18, "男");
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(user);
return str;
}
- 在annationdriver中使用SpringMVC的原生处理中文乱码的问题
<!--JSON乱码问题配置-->
<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>
返回效果:
- 使用@RestController返回字符串(代替@ResponseBody注解,限定整个Controller返回字符串)
package indi.stitch.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import indi.stitch.pojo.User;
import indi.stitch.utils.JSONUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
@RestController
public class UserController {
@RequestMapping("j1")
// @ResponseBody
public String json1() throws JsonProcessingException {
User user = new User("张三", 18, "男");
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(user);
return str;
}
@RequestMapping("j2")
public String json2() throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
List<User> users = new ArrayList<User>();
User user1 = new User("张三", 18, "男");
User user2 = new User("李四", 18, "男");
User user3 = new User("王五", 18, "男");
User user4 = new User("赵六", 18, "男");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
return mapper.writeValueAsString(users);
}
@RequestMapping("j3")
public String json3() throws JsonProcessingException{
Date date = new Date();
String json = JSONUtils.getJson(date, "yyyy-MM-ss HH:mm:ss");
return json;
}
}
- 返回对象集合
@RequestMapping("j2")
public String json2() throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
List<User> users = new ArrayList<User>();
User user1 = new User("张三", 18, "男");
User user2 = new User("李四", 18, "男");
User user3 = new User("王五", 18, "男");
User user4 = new User("赵六", 18, "男");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
return mapper.writeValueAsString(users);
}
返回效果:
- 自定义工具类返回时间对象
默认时间戳,使用SimpleDataFormat(“yy-MM-dd HH:mm:ss”)格式化
使用ObjectMapper.setDateFormat(sdf)可以设置时间格式
使用ObjectMapper.configuer(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)不使用默认时间戳格式
@RequestMapping("j3")
public String json3() throws JsonProcessingException{
Date date = new Date();
String json = JSONUtils.getJson(date, "yyyy-MM-ss HH:mm:ss");
return json;
}
JSONUtils工具类:
package indi.stitch.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 sdf = new SimpleDateFormat(dateFormat);
mapper.setDateFormat(sdf);
try{
return mapper.writeValueAsString(sdf.format(object));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
返回效果: