Spring MVC JSON interaction processing
8, JSON interactive processing
1. What is JSON?
- JS ON (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 hierarchical structure of hydrogen makes JSON an ideal data exchange language;
- Easy to read and write, easy to machine parse and generate, and effectively improve 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
JSON key value pairs are a way to save JavaScript objects, and the writing method is similar to that of JavaScript objects. The key name in the key / value pair combination is written in front and wrapped in double quotation marks "", separated by colon: and then followed by the value:
{"name": "1111"} {"age": "111"} {"sex": "male"}
Many people don't know the relationship between JSON and JavaScript objects, even who is who. In fact, it can be understood as follows:
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 = {a: 'Hello', b: 'World'}; //This is an object. Note that the key name can also be wrapped in quotation marks var json = '{"a": "Hello", "b": "World"}'; //This is a JSON string, which is essentially a string
2. JSON and JavaScript objects interoperate
To convert from a JSON string to a JavaScript 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 JavaScript 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"} '
Operation test
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> //Write an object var user={ name:"Li Chong", age:18, sex:"male" }; //Convert js objects into json objects; var json = JSON.stringify(user); console.log(json) //Convert json objects to JavaScript objects var obj = JSON.parse(json); console.log(obj); </script> </head> <body> </body> </html>
3. JSON data returned by Controller
- Jackson should be a good json parsing tool at present
- Of course, there are more than one tool, such as Alibaba's fastjson and so on
- We use Jackson here. To use Jackson, 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.10.8</version> </dependency>
- Configure the web.xml file
<!--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>
- Configure the springmvc-config.xml file
<?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.lengzher.controller"/> <!-- 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>
- Create entity class
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private int age; private String name; private String sex; }
- Create a controller class and convert an object:
@Controller public class UserController { //Products = "application / JSON; charset = UTF-8" to solve the problem of garbled code @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8") @ResponseBody//He will not go to the view, but will directly return a string public String json1() throws JsonProcessingException { //jackson,ObjectMapper ObjectMapper mapper = new ObjectMapper(); //Create an object User user = new User(1, 18, "Malone", "male"); //Convert object to json string String str = mapper.writeValueAsString(user); return str; } }
- Convert a List collection:
@RequestMapping(value = "/j2") @ResponseBody//He will not go to the view, but will directly return a string for use with @ Controller public String json2() throws JsonProcessingException { //jackson,ObjectMapper ObjectMapper mapper = new ObjectMapper(); ArrayList<User> userList = new ArrayList<User>(); //Create an object User u1 = new User(1, 33, "Malone", "male"); User u2 = new User(2, 33, "zjk", "male"); User u3 = new User(3, 30, "cm", "male"); userList.add(u1); userList.add(u2); userList.add(u3); //Convert collection to json string String str = mapper.writeValueAsString(userList); return str; }
- Conversion time object:
@RequestMapping(value = "/j3") @ResponseBody//He will not go to the view, but will directly return a string for use with @ Controller public String json3() throws JsonProcessingException { //jackson,ObjectMapper ObjectMapper mapper = new ObjectMapper(); //Create a time object Date date = new Date(); //Custom date format SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateFormat = sf.format(date); //ObjectMapper, the default format after time parsing is Timestamp and Timestamp String str = mapper.writeValueAsString(dateFormat); return str; } //Without timestamp @RequestMapping(value = "/j4") @ResponseBody//He will not go to the view, but will directly return a string for use with @ Controller public String json4() throws JsonProcessingException { //jackson,ObjectMapper ObjectMapper mapper = new ObjectMapper(); //Off timestamp mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //Create a time object Date date = new Date(); //Custom date format SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateFormat = sf.format(date); //Convert object to json string String str = mapper.writeValueAsString(dateFormat); return str; }
4. Optimize code
- Solve the problem of garbled Code:
Configure in the springmvc servlet:
<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>
- Extract the common part of the code and encapsulate it into a tool class
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 sf) { //jackson,ObjectMapper ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); mapper.setDateFormat(new SimpleDateFormat(sf)); //Convert object to json string String str = null; try { str = mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return str; } }
When you need to use it, you can call it directly:
//Convert an object @RequestMapping(value = "/j1") @ResponseBody//He will not go to the view, but will directly return a string for use with @ Controller public String json1() throws JsonProcessingException { //Create an object User user = new User(1, 18, "Malone", "male"); //Convert object to json string return JsonUtils.getJson(user); } //Convert time object @RequestMapping(value = "/j4") @ResponseBody//He will not go to the view, but will directly return a string for use with @ Controller public String json4() throws JsonProcessingException { Date date = new Date(); return JsonUtils.getJson(date); }
5,FastJson
- fastjson.jar is a package developed by Ali for Java development,
- Realize the conversion between json object and JavaBean object,
- Realize the conversion between JavaBean object and json string,
- Realize the conversion between json object and json string.
- There are many conversion methods to implement json, and the final implementation results are the same.
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
- Internally, there are methods in the List interface to complete the operation.
- 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.
Use of fastjson:
Import dependency
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency>
Controller class test fastjason
@RequestMapping(value = "/j5") @ResponseBody//He will not go to the view, but will directly return a string for use with @ Controller public String json5() throws JsonProcessingException { ArrayList<User> userList = new ArrayList<User>(); //Create an object User u1 = new User(1, 33, "Malone", "male"); User u2 = new User(2, 33, "zjk", "male"); User u3 = new User(3, 30, "cm", "male"); userList.add(u1); userList.add(u2); userList.add(u3); String s = JSON.toJSONString(userList); return s; }