Version: Next

前后端分离

后端部署后端,提供接口,提供数据

​ JSON

前端独立部署,负责渲染后端的数据

JSON

  • Jackson
  • fastJson

1. 什么是Json

  • JSON(JavaScript Object Notation ,JS对象标记)是一种轻量级的数据交换格式,目前使用广泛
  • 采用完全独立于编程语言的文本格式来存储和表示数据
  • 简洁清晰的结构层次使得JSON成为理想的数据交换语言
  • 可读性强,方便编写,易于解析和生成,提高网络传输效率
  • 对象表示为键值对,数据由,分隔
  • {}保存对象
  • []保存数组
{"name": "Alice"}
{"age": 3}
{"sex": "female"}

JSON 和 JS对象互转

  • JSON -> JavaScript

    var obj = JSON.parse('{"a": "Hello", "b": "World"}');

    -> 结果是 {a: 'Hello', b: 'World'}

  • JavaScript -> JSON

    var json = JSON.stringify({a: 'Hello', b: 'World'});

    -> 结果是 '{"a": "Hello", "b": "World"}'

2. Controller返回JSON数据

2.1 Jackson

2.1.1 JSON乱码问题

可以在SpringMVC的配置文件中的annotation-driven添加一段消息StringHttpMessageConverter转换配置

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

2.1.2 搭建

  • 导入jar包

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</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">
    <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc_servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    </web-app>
  • springmvc_servlet.xml

    <?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 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.bsx.contoller"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    id="internalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    </beans>
  • pojo

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
    private String name;
    private int age;
    private String sex;
    }
  • 方式一:Controller

    • @ResponseBody 不走视图解析器,直接返回一个字符串
  • ObjectMapper 创建ObjectMapper对象,调用writeValueAsString方法将对象转换为Json字符串

    @Controller
    public class UserController {
    @RequestMapping("/j1")
    @ResponseBody // 不会走视图解析器,会直接返回一个字符串
    public String json1() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    User user = new User("名字",18,"男的");
    //转换为Json
    String jsonStr = mapper.writeValueAsString(user);
    return jsonStr;
    }
    }
  • 方式二: RestController 用@RestController注解的Controller类,其中所有的方法都只返回字符串,而不经过视图解析器

    @RestController
    public class UserController {
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    User user = new User("名字",18,"男的");
    //转换为Json
    String jsonStr = mapper.writeValueAsString(user);
    return jsonStr;
    }
    }
  • 测试输出集合对象的JSON

    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    List<User> users = new ArrayList<User>();
    User user1 = new User("名字1",18,"男的1");
    User user2 = new User("名字2",18,"男的2");
    User user3 = new User("名字3",18,"男的3");
    User user4 = new User("名字4",18,"男的4");
    users.add(user1);
    users.add(user2);
    users.add(user3);
    users.add(user4);
    String jsonStr = mapper.writeValueAsString(users);
    return jsonStr;
    }
    //结果
    [{"name":"名字1","age":18,"sex":"男的1"},{"name":"名字2","age":18,"sex":"男的2"},{"name":"名字3","age":18,"sex":"男的3"},{"name":"名字4","age":18,"sex":"男的4"}]
  • 测试输出事件对象

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    Date date = new Date();
    return mapper.writeValueAsString(date);
    }
  • 测试输出时间对象

    • 方式一 JavaSE
    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    Date date = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return mapper.writeValueAsString(simpleDateFormat.format(date));
    }
    "2020-04-15 15:39:53"
    • 方式二 ObjectMapper
    @RequestMapping("/j4")
    public String json4() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    //关闭将时间写为时间戳
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(simpleDateFormat);
    Date date = new Date();
    return mapper.writeValueAsString(date);
    }

2.1.3 Jackson工具类

public class JacksonUtils {
public static String getDateJson(Date date, String dateformat) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateformat);
mapper.setDateFormat(simpleDateFormat);
try {
return mapper.writeValueAsString(date);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}

Controller代码精简为

@RequestMapping("/j5")
public String json5() throws JsonProcessingException {
Date date = new Date();
String dateFormat = "yyyy-MM-dd HH:mm:ss";
String dateJson = JacksonUtils.getDateJson(date, dateFormat);
return dateJson;
}

2.2 Fastjson

Fastjson是阿里巴巴开发的一款专门用于Java开发的包,可以方便的实现Json对象与JavaBean对象的转换,实现JavaBean对象与Json字符串的转换,实现Json对象与Json字符串的转换。

  • Maven坐标

    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
    </dependency>
  • Fastjson三个主要的类

    • JSONObject——表示json对象
      • JSONObject实现了Map接口,猜想JSONObject底层操作是由Map实现的
      • JSONObject对应json对象,通过各种形式的get()方法可以获得json对象中的数据,也可利用注入size(),isEmpty()等方法获取键值对的个数和判断是否为空,其本质是通过Map接口并调用接口种的方法完成的
    • JSONArray——表示json数组对象
      • 内部是由List接口种的方法来完成操作的
    • JSON——表示JSONObject和JSONArray的转化
      • 注意json对象、json对象数组、JavaBean对象,Json字符串之间的相互转化
    @RequestMapping("/j6")
    public String json6() throws JsonProcessingException {
    List<User> users = new ArrayList<User>();
    User user1 = new User("名字1", 18, "男的1");
    User user2 = new User("名字2", 18, "男的2");
    User user3 = new User("名字3", 18, "男的3");
    User user4 = new User("名字4", 18, "男的4");
    users.add(user1);
    users.add(user2);
    users.add(user3);
    users.add(user4);
    String string = JSON.toJSONString(users);
    return string;
    }
  • Json字符串与JavaBean互转

    String jsonStr1 = JSON.toJSONString(user1);
    User user = JSON.parseObject(jsonStr1, User.class);
    System.out.println(user);