SpringMVC学习之Jackson和fastJson将后端数据转换成前端JSON字符串

目录

1、导包

2、配置web.xml

3、配置springmvc-servlet.xml

4、实体类User类

5、Jackson(在UserController类中进行的测试)

5.1、直接使用Jackson

5.2、编写JsonUtils工具类进行测试

6、使用fastjson

1、导包

<dependencies>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
    </dependencies>

2、配置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">

    <servlet>
        <servlet-name>SpringMVC</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>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>

3、配置springmvc-servlet.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://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">

    <!--    自动扫描包,让指定包下的注解生效,由ioc容器统一管理-->
    <context:component-scan base-package="com.zhou.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

<!--    JSON乱码问题配置  只要用了jackson就配置上去-->
    <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>
    <!--    视图解析-->
    <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类

package com.zhou.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;
}

5、Jackson(在UserController类中进行的测试)

5.1、直接使用Jackson

//@Controller 会走视图解析
@RestController  // 直接返回一个字符串
public class UserController {
    @RequestMapping("j1")
    // @ResponseBody // 配合Controller使用的,它就不会走视图解析器,会直接返回一个字符串
    public String json1() throws JsonProcessingException {

        // jackson  ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // 创建一个对象
        User user = new User("xx", 18, "男");

        String str = mapper.writeValueAsString(user);
        return str;
    }
@RequestMapping("j2")
    public String json2() throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();

        List<User> userList = new ArrayList<User>();

        User user1 = new User("xx1", 18, "男");
        User user2 = new User("xx2", 18, "男");
        User user3 = new User("xx3", 18, "男");
        User user4 = new User("xx4", 18, "男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        String str = mapper.writeValueAsString(userList);
        return str;
    }

5.2、编写JsonUtils工具类进行测试

package com.zhou.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){
        return getJson(object, "yyyy-MM-dd HH:mm:dd");
    }

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

        // 不使用时间戳方式
        mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
        // 自定义格式
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
@RequestMapping("j2")
    public String json2() throws JsonProcessingException {

        List<User> userList = new ArrayList<User>();

        User user1 = new User("xx1", 18, "男");
        User user2 = new User("xx2", 18, "男");
        User user3 = new User("xx3", 18, "男");
        User user4 = new User("xx4", 18, "男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        return JsonUtils.getJson(userList);
    }
@RequestMapping("j3")
    public String json3() throws JsonProcessingException {

        Date date = new Date();
        return JsonUtils.getJson(date, "yyyy-MM-dd HH:mm:dd");
    }

6、使用fastjson

 @RequestMapping("j4")
    public String json4() throws JsonProcessingException {

        List<User> userList = new ArrayList<User>();

        User user1 = new User("xx1", 18, "男");
        User user2 = new User("xx2", 18, "男");
        User user3 = new User("xx3", 18, "男");
        User user4 = new User("xx4", 18, "男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        String str = JSON.toJSONString(userList);  // 这个JSON是alibaba包的
        return str;

    }
@RequestMapping("j5")
    public String json5() throws JsonProcessingException {

        List<User> userList = new ArrayList<User>();

        User user1 = new User("xx1", 18, "男");
        User user2 = new User("xx2", 18, "男");
        User user3 = new User("xx3", 18, "男");
        User user4 = new User("xx4", 18, "男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        System.out.println("******java对象 转 JSON字符串******");
        String str1 = JSON.toJSONString(userList);
        System.out.println("JSON.toJSONString(userList)--->" + str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println("JSON.toJSONString(userList)--->" + str2);

        System.out.println("******JSON字符串 转 java对象 ******");
        User user2_object = JSON.parseObject(str2, User.class);
        System.out.println("JSON.parseObject(str2, User.class)--->" + user2_object);

        System.out.println("******java对象 转 JSON对象 ******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println("(JSONObject) JSON.toJSON(user2)--->" + jsonObject1.getString("name"));

        System.out.println("******JSON对象  转  java对象******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)--->" + to_java_user);

        return "hello";

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值