Draw lessons from blogs: https://www.cnblogs.com/hellokuangshen/p/11283224.html
JSON
What is JSON?
What is JSON?
JSON(JavaScript Object Notation, JS Object Markup) is a lightweight data exchange format, which is widely used at present.
Data is stored and represented in a text format completely independent of programming language. The concise and clear hierarchical structure makes JSON an ideal data exchange language. It is easy for people to read and write, and it is also easy for machine parsing and generation, and effectively improves the efficiency of network transmission.
In JS, everything is an object. Therefore, any type supported by JS can be represented by JSON, such as strings, numbers, objects, arrays, etc. Look at his requirements and grammatical format:
Objects are represented as key-value pairs
Data is separated by commas
Curly brackets save objects
Square brackets save arrays
JSON key-value pairs are a way to save JS objects. They are similar to JS objects in writing. Key names in key/value pair combinations are written in front and wrapped in double quotation marks, using colons: separated, followed by values:
{"name": "QinJiang"} {"age": "3"} {"sex": "male"}
Many people don't know the relationship between JSON and Js objects, or even who they are. In fact, it can be understood as follows:
JSON is a string representation of JS objects. It uses text to represent the information of a JS object, which is essentially a string.
var obj = {a: 'Hello', b: 'World'}; //This is an object. Note that key names can also be wrapped in quotation marks. var json = '{"a": "Hello", "b": "World"}'; //This is a JSON string, essentially a string.
JSON and JS Object Interchange
To convert a JSON string to a JS object, use the JSON.parse() method:
var obj = JSON.parse('{"a": "Hello", "b": "World"}'); //The result is {a:'Hello', b:'World'}
To convert from a JS object to a JSON string, use the JSON.stringify() method:
var json = JSON.stringify({a: 'Hello', b: 'World'}); //The result is'{a':'Hello','b':'World'}'
Let's test in the code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JSON_Qin Jiang</title> </head> <body> <script type="text/javascript"> //Write a js object var user = { name:"Qin Jiang", age:3, sex:"male" }; //Converting js objects to json strings var str = JSON.stringify(user); console.log(str); //Converting json strings to js objects var user2 = JSON.parse(str); console.log(user2.age,user2.name,user2.sex); </script> </body> </html>
Result:
Return JSON data using Controller
Jackson should be a better json parsing tool at present, of course, there is more than this tool, such as Alibaba's fastjson and so on.
We use Jackson here. To use it, we 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>
Let's write a User entity class at random, and then we'll write our test Controller; here we need two new things, one is @ResponseBody, and the other is ObjectMapper object. Let's look at the specific usage.
package com.kuang.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kuang.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("/json1") @ResponseBody public String json1() throws JsonProcessingException { //Create an object mapper for jackson to parse data ObjectMapper mapper = new ObjectMapper(); //Create an object User user = new User("Qinjiang No.1", 3, "male"); //Parsing our objects into json format String str = mapper.writeValueAsString(user); return str; //Because of the @ResponseBody annotation, str is returned in json format; it's very convenient. } }
Operation results:
Json Random Code Processing
Method 1:
Single Solution
You can see that there is a scrambling problem:
We need to set his encoding format to utf-8 and the type it returns; we need to modify the code by implementing the produces attribute of @RequestMaping
//produces: Specifies the return type and encoding of the response volume @RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")
Run again:
Method 2
Once and for all
The previous method is more cumbersome. If there are many requests in the project, each one should be added. It can be specified uniformly through Spring configuration, so that it does not need to be processed every time.
<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>
Under test:
@RequestMapping(value = "/json3") @ResponseBody public String json3() throws JsonProcessingException { List<User> list = new ArrayList<>(); User user1 = new User("Qinjiang No.1",1,"male"); User user2 = new User("Qinjiang 2",1,"male"); User user3 = new User("Qinjiang No.3",1,"male"); User user4 = new User("No.4 Qinjiang",1,"male"); list.add(user1); list.add(user2); list.add(user3); list.add(user4); return new ObjectMapper().writeValueAsString(list); }
Result:
We can see that the random code is perfectly solved.
Project Case Realization
Project structure:
pom.xml:
<?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.kuang</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>demo06_springmvc_ajax_json</artifactId> <packaging>war</packaging> <name>demo06_springmvc_ajax_json Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> </dependencies> <build> <finalName>demo06_springmvc_ajax_json</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
dao layer:
package com.kuang.pojo; public class User { private String name; private int age; private String sex; public User() { } public User(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } }
utils:
package com.kuang.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(); //1. How to keep him from returning the timestamp! So we need to turn off its timestamp function. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //2. Time formatting! Self-defined date format object; SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); //3. Let mapper specify the time and date format as simpleDateFormat; mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } }
UserController:
package com.kuang.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.kuang.pojo.User; import com.kuang.utils.JsonUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class UserController { @RequestMapping("/json1") //Think about it. We normally go back to the view parser, and json needs to return a string. //There are many third-party jar packages on the market that can achieve this function, jackson. It only needs a simple annotation to achieve it. //@ ResponseBody, which converts the returned object from the server into a json object to respond back. @ResponseBody public String json1() throws JsonProcessingException { //A jackson object mapper is needed, which is a class that can directly convert objects into json strings. ObjectMapper mapper = new ObjectMapper(); //Create an object User user = new User("Qinjiang No.1",1,"male"); System.out.println(user); //Convert Java objects to json strings; String str = mapper.writeValueAsString(user); System.out.println(str); return str; //Because of the @ResponseBody annotation, it is very convenient to return str in json format. } //Find a problem, random code, how to solve it? Add an attribute to @RequestMapping // // We need to set his encoding format to utf-8 and the type it returns. // // Modify the code by using the produces attribute of @RequestMaping // // produces: Specifies the return type and encoding of the response volume @RequestMapping(value = "/json2",produces = "application/json;charset=utf-8") @ResponseBody public String json2() throws JsonProcessingException { User user = new User("Qinjiang No.1",1,"male"); return new ObjectMapper().writeValueAsString(user); } @RequestMapping(value = "/json3") @ResponseBody public String json3() throws JsonProcessingException { List<User> list = new ArrayList<>(); User user1 = new User("Qinjiang No.1",1,"male"); User user2 = new User("Qinjiang 2",1,"male"); User user3 = new User("Qinjiang No.3",1,"male"); User user4 = new User("No.4 Qinjiang",1,"male"); list.add(user1); list.add(user2); list.add(user3); list.add(user4); return new ObjectMapper().writeValueAsString(list); } @RequestMapping(value = "/time1") @ResponseBody public String json4() throws JsonProcessingException { Date date = new Date(); System.out.println(date); //Problem Finding: The json string returned by default has become a timestamp format: 1564711481926 Timestamp. return new ObjectMapper().writeValueAsString(date); } @RequestMapping(value = "/time2") @ResponseBody public String json5() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); //1. How to keep him from returning the timestamp! So we need to turn off its timestamp function. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //2. Time formatting! Self-defined date format object; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //3. Let mapper specify the time and date format as simpleDateFormat; mapper.setDateFormat(sdf); //Write a date object Date date = new Date(); return mapper.writeValueAsString(date); } //Find problems, repeat too much code, write a tool class for it; @RequestMapping(value = "/time3") @ResponseBody public String json6() throws JsonProcessingException { return JsonUtils.getJson(new Date()); } }
web.xml configuration
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.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> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--Configure filters--> <filter> <filter-name>myFilter</filter-name> <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>--> <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> <!--/* Include.jsp--> <filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
resources:
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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.kuang.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven> <!-- JSON Processing Method of Format Scrambling--> <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>
Jason test time problem solving
controller:
@RequestMapping(value = "/time1") @ResponseBody public String json4() throws JsonProcessingException { Date date = new Date(); System.out.println(date); //Problem Finding: The json string returned by default has become a timestamp format: 1564711481926 Timestamp. return new ObjectMapper().writeValueAsString(date); }
Operation results:
Problem Finding: The json string returned by default becomes a timestamp format:
Solution
@RequestMapping(value = "/time2") @ResponseBody public String json5() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); //1. How to keep him from returning the timestamp! So we need to turn off its timestamp function. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //2. Time formatting! Self-defined date format object; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //3. Let mapper specify the time and date format as simpleDateFormat; mapper.setDateFormat(sdf); //Write a date object Date date = new Date(); return mapper.writeValueAsString(date); }
Operation results
For the sake of code simplicity, we wrote a tool class:
Jsonutils
package com.kuang.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(); //1. How to keep him from returning the timestamp! So we need to turn off its timestamp function. mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //2. Time formatting! Self-defined date format object; SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); //3. Let mapper specify the time and date format as simpleDateFormat; mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } }
controller:
//Find problems, repeat too much code, write a tool class for it; @RequestMapping(value = "/time3") @ResponseBody public String json6() throws JsonProcessingException { return JsonUtils.getJson(new Date()); } }
Operation results: