Introduction and use of Jason

The role of Jason

Era of front and rear end separation:

The backend deploys the backend, provides interfaces, and provides data:

Json

The front end is deployed independently and is responsible for rendering the data of the back end:

1. What is Jason

  • JSON (JavaScript object notation) is a lightweight data exchange format, which is widely used at present.

  • Data is stored and represented in a text format completely independent of the programming language.

  • The concise and clear hierarchy makes JSON an ideal data exchange language.

  • It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

In the JavaScript language, everything is an object. Therefore, any type supported by JavaScript can be represented by JSON, such as string, number, object, array, etc. Look at his requirements and syntax format:

  • Objects are represented as key value pairs, and data is separated by commas

  • Curly braces save objects

  • Square brackets hold the array

The key names in the key / value pair combination are written in front and wrapped in double quotation marks "", separated by colon:, followed by the value:

For example: {"name": "zhang", "age": "28"}

Relationship between JSON and JavaScript objects:

JSON is a string representation of JavaScript objects. It uses text to represent the information of a JS object, which is essentially a string.

var obj = {name: 'zhang', age: '28'}; / / this is an object. Note that the key name can also be wrapped in quotation marks

var json = '{"name": 'zhang', "age": "28"}'; // This is a JSON string, which is essentially a string.

2. Conversion of JSON and JavaScript objects

  • To convert from a JSON string to a JavaScript object, use JSON Parse() method:
  • To convert from a JavaScript string to a JSON object, use JSON Stringify() method:

 json.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON</title>
    <script ype="text/javasctipr"> 
        // Create a JavaScript object
        var user = {
            name: 'zhang',
            age: 28 ,
            id: '888'
        }
        // Print user object
        console.log(user);
        console.log('===================');
        // Convert user to JSON object
        var json = JSON.stringify(user);
        console.log(json);
        console.log('===================');
        // Convert json to JavaScript object
        var obj = JSON.parse(json);
        console.log(obj);
    </script>
</head>
<body>
</body>
</html>

Open with the browser and F12 to open the development debugging tool

 3. JSON data returned by controller

Jackson should be a good json parsing tool at present. There are also some other tools, such as Ali's fatjson

pom. Add Jackson dependency and Lombok dependency in XML. Lombok plug-in needs to be installed to use Lombok dependency

Installation method: File → Settings → Plugins, enter Lombok. If it is not found locally, you can click Search in repositories (or directly click Browse repositories to enter the search). After Lombok is found, select Install to install. After installation, restart the IDEA.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>com.zhang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springmvc-json</artifactId>
    <dependencies>
        <!--Jackson rely on-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>
</project>

Add a web framework, right-click the module item and select Add Framework Support → check Web Application → OK

Configure web XML to configure the dispatcher servlet and filter

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

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

Create spring MVC 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-3.0.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--Automatically scan the package and specify that the comments under the package take effect,from IOC Unified container management-->
    <context:component-scan base-package="com.zhang.controller"/>
    <!--Give Way SpringMVC Do not process static resources .css .js .html .mp3 .mp4-->
    <mvc:default-servlet-handler/>
    <!--One sentence automatic completion DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter Injection of two instances (for use)@RequestMapping (note)-->
    <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>

3.1 annotate the toString method with @ ResponseBody

The method marked with @ ResponseBody will not go to the view parser and directly return a string

UserController.java

package com.zhang.controller;

import com.zhang.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 {
    @RequestMapping("/j1")
    @ResponseBody //If you use @ ResponseBody, you will not go to the view parser and directly return a string
    public String json1(){
        User user = new User("Slow response", 28, "male");
        return user.toString();
    }
}

User.java

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

Configure tomcat and start the service (create lib folder and add libary)

Request path: localhost:8080/j1

result:

Solve the problem of garbled Code: use the produces parameter in the @ RequestMapping annotation to set the type of text

package com.zhang.controller;

import com.zhang.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 {
    @RequestMapping(value="/j1", produces = "application/json;charset=utf-8")
    @ResponseBody //If you use @ ResponseBody, you will not go to the view parser and directly return a string
    public String json1(){
        User user = new User("Slow response", 28, "male");
        return user.toString();
    }
}

Results:

If it is too cumbersome to configure products in each method, spring MVC can configure it directly in annotation driven

<?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-3.0.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--Automatically scan the package and specify that the comments under the package take effect,from IOC Unified container management-->
    <context:component-scan base-package="com.zhang.controller"/>
    <!--Give Way SpringMVC Do not process static resources .css .js .html .mp3 .mp4-->
    <mvc:default-servlet-handler/>
    <!--One sentence automatic completion DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter Injection of two instances (for use)@RequestMapping (note)-->
    <mvc:annotation-driven>
        <!--JSON Garbled problem configuration-->
        <mvc:message-converters>
            <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>
    <!--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>

3.2 use @ ResponseBody annotation and ObjectMapper object

UserContoller.java

package com.zhang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.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 {
    @RequestMapping("/j1")
    @ResponseBody //If you use @ ResponseBody, you will not go to the view parser and directly return a string
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("Slow response", 28, "male");
        String str = mapper.writeValueAsString(user);
        return str;
    }
}

result:

3.3 use @ RestController annotation

@All methods under the class marked by RestController will not go to the view parser and directly return a string

 UserController.java

package com.zhang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.zhang.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController //@All methods under the class marked by RestController will not go to the view parser and directly return a string
public class UserController {
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("Slow response", 28, "male");
        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("Slow response half beat 1", 28, "male");
        User user2 = new User("Slow response half beat 2", 28, "male");
        User user3 = new User("Slow response half beat 3", 28, "male");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        String str = mapper.writeValueAsString(userList);
        return str;
    }
    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Date date = new Date();//The extracted time is converted to String type by ObjectMapper, followed by a timestamp, that is, the number of milliseconds from January 1, 1970 to now
        //Custom date format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = mapper.writeValueAsString(sdf.format(date));
        return str;
    }
    @RequestMapping("/j4")
    public String json4() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //Without timestamp
        mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
        //Custom date format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(sdf);
        Date date = new Date();//The time after format is taken directly
        String str = mapper.writeValueAsString(sdf.format(date));
        return str;
    }
}

Results:

Set to JSON, result:

Time to JSON (format 1)

Time to JSON (format 2)

 

 4. Extraction common method

Create the common class jsonutils java

package com.zhang.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:ss");
    }
    public static String getJson(Object object, String dateFormat){
        ObjectMapper mapper = new ObjectMapper();
        //Without timestamp
        mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
        //Custom date format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

UserController.java

package com.zhang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.zhang.pojo.User;
import com.zhang.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController //@All methods under the class marked by RestController will not go to the view parser and directly return a string
public class UserController {
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("Slow response", 28, "male");
        return JsonUtils.getJson(user);
    }
    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<User> userList = new ArrayList<User>();
        User user1 = new User("Slow response half beat 1", 28, "male");
        User user2 = new User("Slow response half beat 2", 28, "male");
        User user3 = new User("Slow response half beat 3", 28, "male");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        return JsonUtils.getJson(userList);
    }
    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        Date date = new Date();
        return JsonUtils.getJson(date);
    }
    @RequestMapping("/j4")
    public String json4() throws JsonProcessingException {
        Date date = new Date();
        return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
    }
}

Keywords: Front-end JSON

Added by navtheace on Mon, 17 Jan 2022 17:04:08 +0200