JSON数据-jackson的使用



首先得知道:使用SpringMVC返回java对象数据时会自动转为json格式传给前端


  • 问题:我想知道springmvc本身就能返回json格式,为什么用第三方jar包,不是多此一举吗?

  • 回答:用第三方jar包的意义并不在于通过后台controller返回json数据给前端,重在接受前台的json数据并且把前台传回来的json数据转化为我们使用的后台java对象


参考链接:https://www.cnblogs.com/yuqiliu/p/12189811.html




1.使用jackson需要先导包

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>


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>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!--springmvc过滤器,防止乱码-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    </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="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"
       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">

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


    <!--视图解析器-->
    <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.UserController:

package com.kakafa.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kakafa.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller //增加了这个注解会走视图解析器
public class UserController {

    //produces = "application/json;charset=utf-8"解决json中文乱码问题
    @RequestMapping(value="/j1",produces = "application/json;charset=utf-8")
    @ResponseBody //增加了这个注解,则这个方法就不会走视图解析器,会直接返回一个字符串
    public String jason1() throws JsonProcessingException {

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

        User user=new User(1,"卡卡","123456");

        String s = mapper.writeValueAsString(user);

        return s;
    }
}



5.利用springmvc统一解决乱码


在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
        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.kakafa.controller"/>

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


    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>


6.@RestController

用@RestController来代替@Controller和@ResponseBody

@RestController //增加了这个注解这个类里面的所有方法都不会走视图解析器,而是返回一个字符串
public class UserController {


    @RequestMapping("/j1")
    public String jason1() throws JsonProcessingException {

        //jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        User user=new User(1,"卡卡","123456");
        String s = mapper.writeValueAsString(user);
        return s;
    }
}

7.创建一个JSON工具类

当多个controller里面多个方法需要用到JSON时,可以提取出公共代码,创建一个JSON工具类

  • JsonUtil:
package com.kakafa.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 JsonUtil {

    public static String getJson(Object o){
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

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

        //不使用时间戳的方式,JSON输出日期类型的字符串,默认是时间戳的形式,因此这里设置为false
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //自定义时间的格式
        SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
        mapper.setDateFormat(sdf);

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

  • UserController
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kakafa.pojo.User;
import com.kakafa.utils.JsonUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;

@RestController //增加了这个注解这个类里面的所有方法都不会走视图解析器,而是返回一个字符串
public class UserController {


    @RequestMapping("/j1")
    public String jason1() throws JsonProcessingException {

        User user=new User(1,"卡卡","123456");
        return JsonUtil.getJson(user);
    }

    @RequestMapping("/j2")
    public String jason2() throws JsonProcessingException {

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

}


posted @   卡卡发  阅读(150)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示