1. Web1.0 era

Early site login, if failed, need to refresh the page, can login again; Don’t click the submit button, don’t know your password is wrong Now most of the site, are local refresh, without reloading the whole page, realize the page updates to register, found that mobile phone number has been registered, but you just entered, no submission, he suggested the = = web2.0 era, one of the most important factor is the Ajax = =

2. What is JSON

With front and back ends separated, data interaction becomes extremely important!

  • JSON(JavaScript Object Notation) is a lightweight data interchange format that is particularly widely used today.
  • Store and represent data in a text format completely independent of the programming language.
  • The simplicity and clarity of the hierarchy make JSON an ideal data exchange language.
  • Easy to read and write, but also easy to machine analysis and generation, and effectively improve the efficiency of network transmission. In the JavaScript language, everything is an object. Therefore, any type that JavaScript supports can be represented by JSON, such as strings, numbers, objects, arrays, and so on. Take a look at his requirements and syntax format:
  • Objects are represented as key-value pairs, and the data is separated by commas, leaving the last data comma-free
  • Curly braces hold the object
  • JSON key-value pairs are a way of storing JavaScript objects, much the same way JavaScript objects are written. The key names in a key-value pair are preceded by double quotation marks “”, separated by a colon:, followed by the value:

    {"name": "RYGAR"} {"age": "18"} {"sex": "male "}

    Many people are confused about the relationship between JSON and JavaScript objects, or even who is who. In fact, you can think of it this way:

JSON is a string representation of a JavaScript object that uses text to represent information about a JS object, essentially a string.

var obj = {a: 'Hello', b: 'World'}; Var json = '{"a": "Hello", "b": "World"}'; var json = 'a": "Hello", "b": "World"}'; // This is a JSON string, which is essentially a string

JSON and JavaScript objects transfer to each other

To convert from a JSON string to a JavaScript object, use the JSON.parse() method:

var obj = JSON.parse('{"a": "Hello", "b": "World"}'); // return {a: 'Hello', b: 'World'}

To convert JavaScript objects to JSON strings, use the json.stringify () method:

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

The test code

1. Create a new module, SpringMVC-05-JSON, and add Web support

2. Create a new JSON-1.html in the web directory and write the test content

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JSON_RYGAR</title> </head> <body> <script Type ="text/javascript"> var user = {name:"RYGAR", age:18, sex:" male "}; // Convert JS object to JSON string var STR = JSSON.stringify (user); console.log(str); Var user2 = json.parse (STR); console.log(user2.age,user2.name,user2.sex); </script> </body> </html>

Controller returns JSON data

Jackson is probably one of the better JSON parsing tools out there

Of course, this is not the only tool, such as Alibaba’s FastJSON and so on.

We use Jackson here, which requires importing its JAR;

<! -- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> < the groupId > com. Fasterxml. Jackson. Core < / groupId > < artifactId > Jackson - databind < / artifactId > < version > 2.9.8 < / version > </dependency>

Configure the configuration required for SpringMVC

web.xml

<? The 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" > <! SpringMVC</servlet-name SpringMVC</servlet-name SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! SpringMVC configuration file location specified by initialization parameter, SpringMVC configuration file location > <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> 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

<? The 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"> <! > <context:component-scan base-package="com.jialidun.controller"/> <! - view the parser - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" id="internalResourceViewResolver"> <! Prefix -- - > < property name = "prefix" value = "/ WEB - INF/JSP/" / > <! -- suffix - > < property name = "suffix" value = "JSP" / > < / bean > < / beans >

We write a random entity class for User, and then we write our test Controller;

package com.jialidun.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @data @allArgconstructor @noArgconstructor public class User {private String name; private int age; private String sex; }

So we need two new things here, one is @responseBody, and one is an objectMapper object, so let’s see how that works

Write a Controller;

@Controller public class UserController {@RequestMapping("/json1") //@ResponseBody () {@RequestMapping("/json1") //@ResponseBody () Public String JSON1 () throws JSONProcessingException {// create Jackson object mappers to convert objects to JSON strings; ObjectMapper mapper = new ObjectMapper(); // create object User User = new User("RYGAR", 18, "male "); / / will parse Java objects becomes a json String format String STR = mapper. WriteValueAsString (user); // The @responseBody annotation is used, and the STR is returned as JSON; Return STR; / /}}

Configure Tomcat and launch the test!

http://localhost:8080/json1



It is found that there is a garbled code problem, we need to set its encoding format to UTF-8, and the type it returns;

Modify the code by producing the @requestMaping property

// Produces: @RequestMapping(value = "/json1", Produces = "application/json "; charset=utf-8")

Test again, http://localhost:8080/json1, garbled question OK!

Optimize the code

The previous method is cumbersome, and if there are many requests in the project, each one needs to be added, which can be specified through the Spring configuration so that you don’t have to deal with them every time!

We can on the configuration file for springmvc add a message StringHttpMessageConverter transformation 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>

Returns a JSON string for unified resolution

Use @RestController directly on your class. This way, all the methods in it will return a JSON string, instead of adding @ResponseBody to each one! We usually use @RestController in our front-end separation development, which is very convenient!

@RestController public class UserController {// Produces: Produces: @RequestMapping(value = "/json2") public String Throws JSON2 () throws JSONProcessingException {// create a Jackson ObjectMapper to address data ObjectMapper = new ObjectMapper(); // create an object where User = new User("RYGAR2 ", 28, "male "); / / will be our object parsing json format String STR = mapper. WriteValueAsString (user); // Because of the @responseBody annotation, we will convert the STR to JSON format and return it; Return STR; }}

Start the Tomcat test, and the results output normally!

Test set output

Add a new method

@requestMapping ("/json3") public String Json3 () throws JsonProcessingException {// JacksonProcessingException { ObjectMapper = new ObjectMapper(); // create an object where user1 = new User(" user1 ", "user1 "); User user2 = new User(" User2 ", "User2 "); User user3 = new User(" user3 ", 23, "male "); User user4 = new User(" User4 ", "User4 "," User4 "); List<User> list = new ArrayList<User>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); / / will be our object parsing json format String STR = mapper. WriteValueAsString (list); return str; }

Results: Perfect, no problems!

Output time object

Add a new method

@RequestMapping("/json4") public String json4() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Java.util.Date Date Date = new Date(); / / will be our object parsing json format String STR = mapper. WriteValueAsString (date); return str; }

  • The default date format becomes a number, which is the number of milliseconds from January 1, 1970 to the current date!
  • By default, Jackson will convert the time into timestamps

Solution: Cancel timestamps and customize the time format

@RequestMapping("/json5") public String json5() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); / / do not use timestamp, default is true, timestamp to false mapper. The configure (SerializationFeature WRITE_DATES_AS_TIMESTAMPS, false); // SimpleDateFormat SDF = new SimpleDateFormat(" yyyy-mm-dd HH: MM :ss"); // Specify the date in mapper.setDateFormat(SDF); // Write a Date object Date Date = new Date(); String str = mapper.writeValueAsString(date); return str; }

Extraction tool class

If you want to use it frequently, which is cumbersome, you can encapsulate the code in a utility class; So let’s write that

package com.jialidun.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(); / / the way of using time difference mapper. The configure (SerializationFeature WRITE_DATES_AS_TIMESTAMPS, false); SDF = new SimpleDateFormat(dateFormat); // Specify the date in mapper.setDateFormat(SDF); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; }}

We use the utility class, the code is more concise!

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

FastJson

FastJSSON. Jar is Ali development of a special package for Java development, you can easily achieve the conversion of JSON objects and JavaBean objects, JavaBean objects and JSON string conversion, JSON objects and JSON string conversion. There are many ways to convert JSON, and the final result is the same.

FastJSON POM dependency!

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

FastJSON has three main classes:

JSONObject stands for JSON object

  • JSONObject implements the Map interface. It is assumed that the underlying operations of JSONObject are implemented by the Map.
  • JSONObjects correspond to JSON objects, and you can get the data in JSON objects through various forms of get() methods, or you can use methods such as size(), isEmpty() to get the number of “key: value” pairs and determine if they are empty. Essentially, this is done by implementing the Map interface and calling methods in the interface.

JSONArray represents an array of JSON objects

  • Internally, there are methods in the List interface to do the operation.

JSON represents the transformation of JSONObject and JSONArray

  • JSON class source code analysis and use
  • Careful observation of these methods, mainly to achieve JSON objects, JSON object array, JavaBean objects, JSON string between the mutual conversion.

To test the code, let’s create a new FastJsonDemo class

package com.jialidun.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 static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args); User user2 = new User(" 1 ", "1 "); User user3 = new User(" ", 3, "); User user4 = new User(" Demacia ", 3, "male "); List<User> list = new ArrayList<User>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); System. The out. Println (" * * * * * * * Java objects turn JSON 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 * * * * * * turn JSON string 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 objects turn JSON object * * * * * * "); JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2); System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name")); System. Out. Println (" \ n * * * * * * a JSON object turn Java object * * * * * * "); User to_java_user = JSON.toJavaObject(jsonObject1, User.class); System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user); }}

This kind of tool class, we only need to master the use of it, in the use of the time in accordance with the specific business to find the corresponding implementation.