Spring MVC -- using Controller to return JSON data

Spring MVC -- using Controller to return JSON data

1. Use Jackson

Jackson: at present, the famous json parsing tool class library

Dependencies imported using Jackson:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.2</version>
        </dependency>

Configuration environment

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

    <!--1.register servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- Start sequence: the smaller the number, the earlier the start -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--All requests will be rejected springmvc intercept -->
    <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>

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

    <!-- Automatically scan the specified package and submit all the following annotation classes to IOC Container management -->
    <context:component-scan base-package="com.cheng.controller"/>

    <mvc:default-servlet-handler />
    <mvc:annotation-driven />
    <!-- view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- suffix -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

1.1. Convert ordinary objects to JSON

We set up a simple Java class with Lombok.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}
@Controller
//@RestController adds this annotation. All methods under this class will not be parsed by the view parser, but will only return a string
public class UserController {

    @ResponseBody//With this annotation, this method will not be parsed by the view parser, but will only return a string
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        //ObjectMapper object, which is required for serialization and deserialization
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("a great distance",3,"male");
        String s = mapper.writeValueAsString(user);//Convert user object to string
        return s;
    }
}

@RestController adds this annotation. All methods under this class will not be parsed by the view parser, but will only return a string

@If this annotation is added to the ResponseBody, this method will not be parsed by the view parser, but will only return a string

Test:

To solve the problem of JSON garbled Code:

Method 1: not recommended

/produces:Specify the return type and encoding of the response body
@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")

Method 2: in spring MVC servlet XML configuration, unified solution, recommended

        <!--solve json Garbled code problem-->
        <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>

1.2. Convert set to JSON

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

        List<User> list = new ArrayList<User>();
        User user1 = new User("Wanli 1",3,"male");
        User user2 = new User("Wanli 2",3,"male");
        User user3 = new User("Wanli 3",3,"male");
        User user4 = new User("Wanli 4",3,"male");

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

        return new ObjectMapper().writeValueAsString(list);
    }

Test:

1.3 time conversion to JSON

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        Date date = new Date();
        return new ObjectMapper().writeValueAsString(date);//The default format after parsing is the timestamp 1618560108079
    }

The default format for parsing time into JSON is timestamp

Custom parsed format

Method 1: use the traditional Java method to solve the problem

   @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date date = new Date();
        return new ObjectMapper().writeValueAsString(sdf.format(date));
    }

Method 2: define the format with ObjectMapper

      @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

        //Turn off using timestamp format
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setDateFormat(sdf);//Custom time format

        Date date = new Date();
        return mapper.writeValueAsString(date);
    }

2. Using Fastjson

fastjson.jar is a package specially developed by Ali for Java development. It can easily realize the conversion between json object and JavaBean object, between JavaBean object and json string, and between json object and json string. There are many conversion methods to realize json, and the final implementation results are the same.

Dependency of importing fastjson: make sure to add jar package in the project structure before using

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

fastjson has three main classes:

  • JSONObject represents a json object

    • JSONObject implements the Map interface. I guess the underlying operation of JSONObject is implemented by Map.
    • JSONObject corresponds to the json object. You can obtain the data in the json object through various forms of get() methods. You can also use methods such as size(), isEmpty() to obtain the number of "key: value" pairs and judge whether they are empty. Its essence is accomplished by implementing the Map interface and calling the methods in the interface.
  • JSONArray represents an array of json objects

    • The internal operation is completed by the methods in the List interface.
  • JSON represents the conversion of JSONObject and JSONArray

    • Analysis and use of JSON class source code
    • Carefully observe these methods, mainly to realize the mutual transformation between json objects, json object arrays, javabean objects and json strings.

Test:

   @RequestMapping("/j4")
    public String json4(){

        List<User> list = new ArrayList<User>();
        User user1 = new User("Wanli 1",3,"male");
        User user2 = new User("Wanli 2",3,"male");
        User user3 = new User("Wanli 3",3,"male");
        User user4 = new User("Wanli 4",3,"male");

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

        System.out.println("*******Java Object transfer JSON character string*******");
        String str1 = JSON.toJSONString(list);
        System.out.println("JSON.toJSONString(list)==>"+str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println("JSON.toJSONString(user1)==>"+str2);

        System.out.println("\n****** JSON String conversion Java object*******");
        User jp_user1=JSON.parseObject(str2,User.class);
        System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

        System.out.println("\n****** Java Object transfer JSON object ******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));

        System.out.println("\n****** JSON Object transfer Java object ******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);

        String s = JSON.toJSONString(list);
        return s;
    }

Keywords: JSON Spring MVC jackson fastjson

Added by khefner on Fri, 04 Mar 2022 19:08:48 +0200