JavaEE(15)JSON、Jackson、FastJson

1. JSON

1. JSON概念
(1)JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式
(2)采用完全独立于编程语言的文本格式来存储和表示数据
(3)简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言
(4)易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率

2. JSON
(1)格式

1. 对象表示为键值对,数据由逗号分隔
2. 花括号保存对象
3. 方括号保存数组
{
     "name":"老王"}
{
     "age":"12"}
{
     "sex","男"}

(2)JSON与JS对象的关系

JSON是JS对象的字符串表示法,他使用文本表示一个JS对象的信息,本质上是一个字符串
var obj = {
     a:'hello',b:'world'};  //JS对象
var str = '{"a":"hello","b","world"}';   //JSON字符串  

(3)JSON字符串与JS对象互转

1. JSON字符串==>JavaScript对象:JSON.parse()
2. JavaScript对象==>JSON字符串:JSON.stringify()

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

body>
html>
<script>

    //JS对象
    var User = {
      
        name : "老王",
        age : 13,
        sex : "男"
    };

    //JS对象转化为JSON字符串
    var str = JSON.stringify(User);
    console.log(str);  //{"name":"老王","age":13,"sex":"男"}

    //再将字符串转化为JS对象
    var obj = JSON.parse(str);
    console.log(obj);   //Object { name: "老王", age: 13, sex: "男" }
script>

2. Controller返回JSON数据:使用Jackson

1. Jackson概念:JSON解析工具
2. 使用
(1)导入jar包


<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.8version>
dependency>

(2)配置web.xml


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

(3)配置spring-servlet.xml


<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.nelws.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    bean>
beans>

(4)编写User实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
     
    private String name;
    private int age;
    private String sex;
}

(5)编写Controller类

@Controller
public class UserController {
     

    @RequestMapping("/j01")
    @ResponseBody  //此注解不会通过视图解析器,会直接返回字符串
    public String json01() throws JsonProcessingException {
     
        //创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("小王", 12, "男");

        //将对象解析成JSON
        String str = mapper.writeValueAsString(user);

        return str;
    }
}

(6)配置tomcat,并测试:http://localhost:8080/j01
在这里插入图片描述
发现有乱码
(7)乱码解决:在springmvc-servlet.xml中添加

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

(8)返回JSON字符串的统一解决:常用
直接在类上使用@RestController。这样子,里面的所有方法都只会返回JSON字符串了,不用再每个类上添加@ResponseBody

@RestController
public class UserController {
     

    @RequestMapping("/j01")
    public String json01() throws JsonProcessingException {
     
        //创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("小王", 12, "男");

        //将对象解析成JSON
        String str = mapper.writeValueAsString(user);

        return str;
    }
}

(9)测试:http://localhost:8080/j01
在这里插入图片描述
3. 测试集合输出
(1)编写Controller类

    @RequestMapping("/j02")
    public String json02() throws JsonProcessingException {
     
        ObjectMapper mapper = new ObjectMapper();
        User user1 = new User("小王1号", 14, "男");
        User user2 = new User("小王2号", 14, "男");
        User user3 = new User("小王3号", 14, "男");
        User user4 = new User("小王4号", 14, "男");

        ArrayList<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);

        String str = mapper.writeValueAsString(list);

        return str;
    }

(2)测试:http://localhost:8080/j02
在这里插入图片描述
4. 测试时间输出
(1)编写Controller类

    @RequestMapping("/j03")
    public String json03() throws JsonProcessingException {
     
        ObjectMapper mapper = new ObjectMapper();

        Date date = new Date();

        //自定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String str = mapper.writeValueAsString(sdf.format(date));

        return str;
    }

(2)测试:http://localhost:8080/j03
在这里插入图片描述
5. 抽取JSON工具类
(1)编写工具类

public class JsonUtil {
     

    public static String getJson(Object object){
     
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object,String dataFormat){
     
        ObjectMapper mapper = new ObjectMapper();

        //不使用时间戳的方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        //自定义日期格式对象
        SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);

        //指定日期格式
        mapper.setDateFormat(sdf);

        try {
     
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
     
            e.printStackTrace();
        }

        return null;

    }
}

(2)编写Controller类

    @RequestMapping("/j04")
    public String json04() throws JsonProcessingException {
     
        Date date = new Date();
        String str = JsonUtil.getJson(date);
        return str;    //"2021-01-11 14:11:30"
    }

    @RequestMapping("/j05")
    public String json05() throws JsonProcessingException {
     
        User user = new User("阿萨德", 11, "男");
        String str = JsonUtil.getJson(user);
        return str;   //{"name":"阿萨德","age":11,"sex":"男"}
    }

(3)测试

3. FastJson

1. 介绍:fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换

2. 使用
(1)添加jar包

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
    <version>1.2.60version>
dependency>

(2)使用

public class FastJsonTest {
     
    public static void main(String[] args) {
     
        User user1 = new User("小王", 14, "男");
        User user2 = new User("小李", 14, "女");

        ArrayList<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);

        System.out.println("=====java对象 转 JSON字符串=====");
        String user_str = JSON.toJSONString(user1);
        String list_str = JSON.toJSONString(list);
        System.out.println(user_str);  //{"age":14,"name":"小王","sex":"男"}
       
        System.out.println(list_str);  //[{"age":14,"name":"小王","sex":"男"},
        							   //{"age":14,"name":"小李","sex":"女"}]

        System.out.println("=====JSON字符串 转 java对象=====");
        User user_obj = JSON.parseObject(user_str, User.class);
        System.out.println(user_obj);   //User(name=小王, age=14, sex=男)

    }
}

你可能感兴趣的:(java)