spring mvc 07——JSON

What is JSON

  • JSON (JavaScript Object Notation, JS object tag) is a lightweight data-interchange format, in particular widely used at present.
  • A fully independent programming language text format to represent and store data.
  • Simple and clear hierarchy make JSON an ideal data-interchange language.
  • Easy to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.

In the JavaScript language, everything is an object. Thus, any type of support JavaScript can be represented by the JSON, such as strings, numbers, objects, arrays and the like. Look at his request and syntax:

  • Objects are represented as key-value pairs of data separated by a comma
  • Save Object braces
  • Save array square brackets

JSON key-value pair wording is one way to save the JavaScript object, and also similar JavaScript object, key / value pair combination EDITORIAL keys and double quotation marks "" package, colon: the partition, and then followed by value:

{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}

The relationship between JSON and JavaScript objects:

  • JSON JavaScript object string representation, which represent text information using a JS object is essentially a string.

    var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
    var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON 字符串,本质是一个字符串

JSON and JavaScript object system conversion:

  • To achieve the JSON string into a JavaScript object, using the JSON.parse () Method:

    var obj = JSON.parse('{"a": "Hello", "b": "World"}'); 
    //结果是 {a: 'Hello', b: 'World'}
  • To achieve the conversion from a JavaScript object JSON string using the JSON.stringify () Method:

    var json = JSON.stringify({a: 'Hello', b: 'World'});
    //结果是 '{"a": "Hello", "b": "World"}'

Code Testing

  1. Create a json-1.html in the web directory, write test content

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>JSON_秦疆</title>
    </head>
    <body>
    
    <script type="text/javascript">
    //编写一个js的对象
    var user = {
     name:"黄大姐",
     age:25,
     sex:"女"
    };
    //将js对象转换成json字符串
    var str = JSON.stringify(user);
    console.log(str);
    
    //将json字符串转换为js对象
    var user2 = JSON.parse(str);
    console.log(user2.age,user2.name,user2.sex);
    
    </script>
    
    </body>
    </html>
  2. IDEA opened in a browser, view the console output!

Controller returns JSON data

  • Jackson should now be better analytical tool for the json

  • Of course, this is more than a tool, such as Alibaba also fastjson and so on.

  • We use here Jackson, use it need to import its jar package;

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>
  • SpringMVC configuration needed to configure
    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.注册servlet-->
        <servlet>
            <servlet-name>SpringMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
            <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>
    
        <!--所有请求都会被springmvc拦截 -->
        <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">

    <!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
    <context:component-scan base-package="com.xiaohua.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>
  • We just write a User entity class, and then we have to write our test Controller;

    package com.kuang.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    //需要导入lombok
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
    
        private String name;
        private int age;
        private String sex;
    
    }
  • Here we need two new things, one is @ResponseBody, is a ObjectMapper object we look at the specific usage

Writing a Controller;

@Controller
public class UserController {

    @RequestMapping("/json1")
    @ResponseBody
    public String json1() throws JsonProcessingException {
        //创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("黄大姐", 25, "女");
        //将我们的对象解析成为json格式
        String str = mapper.writeValueAsString(user);
        //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
        return str;
    }

}
  • Configuring Tomcat, start the test!

  • Found there was garbage problem, we need to set about his coding format utf-8, and the type of its return;

  • Produces @RequestMaping achieved by the attribute, the code modifications

    //produces:指定响应体返回类型和编码
    @RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")
  • Test again, HTTP: // localhost : 8080 / json1, garbled OK!

== [Note: Remember to use json deal with the garbage problem] ==

Code optimization

Garbled unified solution

On a way more trouble, if there are many requests then each must add a project, you can specify unified by the Spring configuration, so you do not always have to deal with!

We can add some news StringHttpMessageConverter on springmvc configuration file conversion configuration!

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

Return json string unified solution

Used on classes directly @RestController , like this, all of which method will only return json string, and do not have to add each @ResponseBody! We separate back-end development front, generally use @RestController, very convenient!

@RestController
public class UserController {

    //produces:指定响应体返回类型和编码
    @RequestMapping(value = "/json1")
    public String json1() throws JsonProcessingException {
        //创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("黄大姐", 25, "女");
        //将我们的对象解析成为json格式
        String str = mapper.writeValueAsString(user);
        //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
        return str;
    }

}

Tomcat start test, the results are output to normal!

Collective output

Add a new approach

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

    //创建一个jackson的对象映射器,用来解析数据
    ObjectMapper mapper = new ObjectMapper();
    //创建一个对象
    User user1 = new User("黄大姐", 25, "女");
    User user2 = new User("黄小姐", 25, "女");
    List<User> list = new ArrayList<User>();
    list.add(user1);
    list.add(user2);

    //将我们的对象解析成为json格式
    String str = mapper.writeValueAsString(list);
    return str;
}

Time plant output

Add a new approach

@RequestMapping("/json3")
public String json3() throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();

    //创建时间一个对象,java.util.Date
    Date date = new Date();
    //将我们的对象解析成为json格式
    String str = mapper.writeValueAsString(date);
    return str;
}

operation result :

  • The default date format will become a figure is the number of milliseconds January 1, 1970 to the current date!
  • Jackson is the default time will turn into timestamps form

Solution: Cancel timestamps form, custom time format

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

    ObjectMapper mapper = new ObjectMapper();

    //不使用时间戳的方式
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    //自定义日期格式对象
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //指定日期格式
    mapper.setDateFormat(sdf);

    Date date = new Date();
    String str = mapper.writeValueAsString(date);

    return str;
}

The result: the successful export time!

As a tool to extract class

If you frequently use the words, this is too much trouble, and we can use these tools code is encapsulated into a class; we went down to write

package com.xiaohua.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();
        //不使用时间差的方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //自定义日期格式对象
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        //指定日期格式
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

We use tools, code more concise!

@RequestMapping("/json5")
public String json5() throws JsonProcessingException {
    Date date = new Date();
    String json = JsonUtils.getJson(date);
    return json;
}

Fast Json

fastjson.jar Ali is dedicated to the development of a Java development package, can easily achieve the conversion json object JavaBean objects to achieve the object conversion JavaBean with a string of json, and json achieve json object into a string. Json method to achieve the conversion of many, the realization of the final result is the same.

fastjson of pom-dependent!

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

fastjson three main categories:

  • [JSONObject on behalf of json objects]
    • JSONObject implements Map, suppose the underlying operating JSONObject Map is implemented.
    • JSONObject corresponds json object, through various forms of get () method gets the data json object, may also be utilized, such as size (), isEmpty () Gets the like "key: value" pairs and determines whether the number of empty . Its essence is through the implementation of the Map interface and call interface methods to complete.
  • [JSONArray representatives json object array]
    • List internal interface method is to complete the operation.
  • [JSON conversion JSONObject and representatives of JSONArray]
    • JSON class source code analysis and use
    • Careful observation of these methods, the object is to achieve json, json mutual conversion between an array of objects, the object JavaBean, json string.

Code testing, we create a new class FastJsonDemo

package com.xiaohua.controller;

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

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

public class FastJsonDemo {
    public static void main(String[] args) {
        //创建一个对象
        User user1 = new User("黄大姐", 25, "女");
        User user2 = new User("黄大姐", 25, "女");
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);

        System.out.println("*******Java对象 转 JSON字符串*******");
        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字符串 转 Java对象*******");
        User jp_user1=JSON.parseObject(str2,User.class);
        System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

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

        System.out.println("\n****** JSON对象 转 Java对象 ******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
    }
}

Guess you like

Origin www.cnblogs.com/huangdajie/p/12522194.html