【SpringMVC】JSON以及Fastjson和Jackson的使用

基本要点

1、什么是Json

1、定义
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成

2、语法

  • 对象表示为键值对,字段由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

{“name”:“十年”,“age”:18,“sex”:“男”}
[{“name”:“十年”,“age”:18,“sex”:“男”},{“name”:“decade”,“age”:20,“sex”:“女”}]

2、关于Jackson的使用

新建module,添加web支持,可以参考我之前的博客 【SpringMVC】MVC架构与Servlet
先导入相关依赖

<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.9version>
dependency>
<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.22version>
    <scope>providedscope>
dependency>

然后我们配置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>DispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc-servlet.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    <filter>
        <filter-name>CharacterEncodingFilterfilter-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>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
web-app>

和springmvc的配置文件springmvc-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.decade4.controller"/>
    
    <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>
    
    <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>

首先我们编写一个工具类JacksonUtil.java,用于将string字符串转换成json格式

package com.decade4.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JacksonUtil {

    /**
     * ObjectMapper初始化,创建一个jackson的对象映射器,用来解析数据
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private JacksonUtil() { }

    public static ObjectMapper getInstance() {
        return MAPPER;
    }

    /**
     * 将对象转换成json字符串
     * @param obj 需要转换的对象
     * @return 转换后的json字符串
     */
    public static String objectToString(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            throw new RuntimeException("对象转换成json字符串错误", e);
        }
    }
}

另外还需要一个实体类User.java

package com.decade4.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

在使用下方注解时,控制器中的接口不会往视图跳转,它会直接返回字符串,我们使用工具类将字符串转换成JSON格式

@RestController

package com.decade4.controller;

import com.decade4.pojo.User;
import com.decade4.util.JacksonUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController2 {

    @GetMapping(value = "/rest")
    public String test() {
        User user = new User("十年", 18, "男");
        return JacksonUtil.objectToString(user);
    }
}

使用http://localhost:8080/rest测试如下
【SpringMVC】JSON以及Fastjson和Jackson的使用_第1张图片

@Controller + @ResponseBody

package com.decade4.controller;

import com.decade4.pojo.User;
import com.decade4.util.JacksonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class TestController {

    @GetMapping(value = "/rest2")
    @ResponseBody
    public String test() {
        List<User> users = new ArrayList<User>();

        User user = new User("十年", 18, "男");
        User user2 = new User("decade", 20, "女");
        users.add(user);
        users.add(user2);

        return JacksonUtil.objectToString(users);
    }
}

使用http://localhost:8080/rest2测试如下
【SpringMVC】JSON以及Fastjson和Jackson的使用_第2张图片

3、JSON乱码问题的解决

在springmvc配置文件中更改配置mvc:annotation-driven配置项

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

或者使用原生的方式,在接口上的注解改为

//produces:指定响应体返回类型和编码
@RequestMapping(value = "/rest",produces = "application/json;charset=utf-8")

4、Fastjson

首先我们导入依赖

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

然后我们在上面的模块中写一个测试类,了解一下常用的方法

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.decade4.pojo.User;

import java.util.ArrayList;
import java.util.List;

public class MyTest {
    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();

        User user = new User("十年", 18, "男");
        User user2 = new User("decade", 20, "女");
        users.add(user);
        users.add(user2);

        System.out.println("========java对象转json字符串===========");
        String string = JSON.toJSONString(user);
        System.out.println(string);
        System.out.println(JSON.toJSONString(users));

        System.out.println("========json字符串转Java对象===========");
        User userInfo = JSON.parseObject(string, User.class);
        System.out.println(userInfo);

        System.out.println("========java对象 转 jSON对象===========");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user);
        System.out.println(jsonObject1.getString("age"));

        System.out.println("========jSON对象 转 java对象========");
        User userFormJson = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println(userFormJson);
    }
}

运行结果如下
【SpringMVC】JSON以及Fastjson和Jackson的使用_第3张图片

其实之前我做的项目已经不用JsonObject了,都是使用上面Jackson里面的JsonNode
后面我会整理相关用法到本博客

如有错误,欢迎指正!

你可能感兴趣的:(SpringMVC,java,后端,开发语言,SpringMVC)