What is a JSON?

  • JSON (JavaScript Object Notation) is a lightweight data interchange format that is widely used today.
  • Data is stored and represented in a text format that is 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 parsing and generation, and effectively improve the efficiency of network transmission.

In JavaScript, everything is an object. Therefore, any type supported by JavaScript can be represented through JSON, such as strings, numbers, objects, arrays, and so on. Take a look at his requirements and syntax:

  • Objects are represented as key-value pairs, with data separated by commas
  • Curly braces save objects
  • Square brackets hold arrays

JSON key-value pairs are a way to store JavaScript objects, and are written in much the same way as JavaScript objects. The key/value pair combinations are preceded by the key name and enclosed in double quotation marks (“), separated by a colon:, followed by the value:

{"name":"zhangsan"}
{"age":"3"}
{"sex":"Male"}

Copy the code
  • JSON is a string representation of a JavaScript object, which uses text to represent information about a JS object, essentially a string.
var obj = {a:'Hello',b:'World'}; // This is an object. Note that the key name is also var json =, which can be wrapped in quotes'{a:"Hello",b:"World"}'; // This is a JSON string, essentially a stringCopy the code

JSON and JavaScript objects rotate 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"}'); // the result is {a:'Hello',b:'World'}

Copy the code
  • To convert a JavaScript object to a JSON string, use the json.stringify () method:
var json = JSON.stringify({a:'Hello',b:'World'}); / / as a result'{a:"Hello",b:"World"}'

Copy the code

The test code

  1. Create a new module, Spring-05-json, and add Web support
  2. Create a new jsontest.html file in the Web directory and write the test
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script type="text/javascript"> // Write a JavaScript object var user={name:"Zhang",
            age:3,
            sex:"Male"}; console.log(user); // Convert a js object to a JSON object; var json = JSON.stringify(user); console.log(json); // Convert json objects to JS objects; var obj = JSON.parse(json); console.log(obj); </script> </head> <body> </body> </html>Copy the code
  1. Open in a browser in IDEA and view the console output.

Controller returns JSON data

  • Jackson is probably the best TOOL for JSON parsing right now
  • Of course, the tool is not only this one, such as Alibaba fastjson and so on.
  • We use Jackson here, which requires importing its JAR package.

Jackson

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> The < version > 2.9.9 < / version > < / dependency >Copy the code
  • Configuration files required to configure SpringMVC

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"> <! <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! Specify the location of the SpringMVC configuration file with the initialization parameter. > <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> <! -- All requests will be blocked by springMVC --> <servlet-mapping> <servlet-name> springmvc </servlet-name> <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>Copy the code

springmvc.xml

<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <! <context:component-scan base-package="com.kuang.controller"/ > <! Let springMVC not handle static resources --> < MVC :default-servlet-handler/> <! -- Enable annotation support --> < MVC :annotation-driven/> <! -- Configure the view parser --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <! -- prefix resolver --> <property name="prefix" value="/WEB-INF/jsp/"></property> <! -- suffix resolver --> <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

Copy the code
  • Write a User entity class
Lombok @data @allargsconstructor @noargsconstructor public class User {private String name; private int age; private String sex; }Copy the code
  • Write a test class, Controller
@Controller
public class UserController {
    @RequestMapping("/json1") @responseBody // He doesn't go to the view parser, Public String jSON1 () throws Exception{// Jackson ObjectMapper mapper =new ObjectMapper(); User user = new User("Zhang SAN 01", 21,"Male");
        String str = mapper.writeValueAsString(user);
        returnstr; }}Copy the code

Configure Tomcat and start testing it!

http://localhost:8080/json1

We need to set its encoding format to UTF-8 and the type it returns.

To implement this using the @requestMapping produces attribute, modify the following code:

// Produces: Specifies the return type and encoding of the response body @requestMapping (value = produces)"/json1",produces = "application/json; charset=utf-8")

Copy the code

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

Garbled code unified solution

If there are many requests in your project and you need to add each one, you can specify them through the Spring configuration so 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>

Copy the code

Return JSON string unified solution

Use @restController directly on your class, and then all of the methods in there will just return a JSON string, so instead of adding @responseBody to every one of them! We usually use @RestController in front – and – back development, which is very convenient!

@restController public class UserController {// Produces: Specifies the return type and encoding of the response body @requestMapping (value = Produces)"/json1") public String json1() throws JsonProcessingException {// Create a Jackson object mapper, ObjectMapper mapper = new ObjectMapper(); // create an object User = new User("Joe Three one.", 3, "Male"); / / will be our object parsing json format String STR = mapper. WriteValueAsString (user); // Because of the @responseBody annotation, the STR is returned as json; It is very convenientreturnstr; }}Copy the code

Start tomcat test, the results are normal output!

Test set output

Add a new method

@RequestMapping("/json2") @responseBody // He doesn't go to the view parser, Public String jSON2 () throws Exception{// Jackson ObjectMapper mapper =new ObjectMapper(); List<User> userList = new ArrayList<User>(); User user1 = new User("Zhang SAN 01", 21,"Male");
    User user2 = new User("Zhang SAN.", 21,"Male");
    User user3 = new User("Zhang SAN 03", 21,"Male");
    User user4 = new User("Zhang SAN 04", 21,"Male");

    userList.add(user1);
    userList.add(user2);
    userList.add(user3);
    userList.add(user4);

    String str = mapper.writeValueAsString(userList);
    return str;
}

Copy the code

Run result: no problem!

Output time object

Add a new method

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

Copy the code

Running results:

  • The default date format becomes a number, the number of milliseconds from January 1, 1970 to the current date!
  • Jackson defaults to timestamps

Solution 1: Use SimpleDateFormat to customize the time format

@RequestMapping("/json3") @responseBody // He doesn't go to the view parser, Public String jSON3 () throws Exception {// Jackson ObjectMapper mapper = new ObjectMapper(); Date date = new Date(); SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");

  return mapper.writeValueAsString(sdf.format(date));
}

Copy the code

Solution 2: Cancel the timestamps format and customize the time format

@RequestMapping("/json4") @responseBody // He doesn't go to the view parser, Public String jSON4 () throws Exception {// Jackson ObjectMapper mapper = new ObjectMapper(); / / do not use timestamp, mapper. The configure (SerializationFeature WRITE_DATES_AS_TIMESTAMPS,false); SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
  mapper.setDateFormat(sdf);

  Date date = new Date();
  return mapper.writeValueAsString(date);
}

Copy the code

Run result: output time successfully!

Extract into utility classes

This is more cumbersome if you want to use it more often, so you can wrap this code in a utility class; So let’s write it

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){ //jackson ObjectMapper mapper = new ObjectMapper(); / / do not use the timestamp mapper. The 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();
        }
        returnnull; }}Copy the code

The code is much cleaner now.

@RequestMapping("/json5"Public String json5() throws Exception {Date Date = new Date();return JSONUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
}

Copy the code

FastJson

Fastjson. jar is a package developed by Ali specially for Java development, which can easily realize the conversion between JSON objects and JavaBean objects, JavaBean objects and JSON strings, and REALIZE the conversion between JSON objects and JSON strings. There are many ways to convert json, and the end result is the same.

Import POM dependencies

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

Copy the code

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 Map.
    • JSONObject corresponds to a JSON object. The data in the JSON object can be obtained through various forms of get() method, and the number of “key: value” pairs can also be obtained by methods such as size() and isEmpty() to determine whether they are empty. This is essentially done by implementing the Map interface and calling the methods in the interface.
  • JSONArray stands for ARRAY of JSON objects
    • Internally, there are methods in the List interface to do this.
  • JSON stands for JSONObject and JSONArray.
    • JSON class source code analysis and use.
    • Take a closer look at these methods, mainly to achieve json objects, JSON object arrays, Javabean objects, JSON strings between the conversion.

Code test:

@RequestMapping("/json6")
@ResponseBody
public String json6() throws Exception {
  List<User> userList = new ArrayList<User>();
  User user1 = new User("Zhang SAN 01", 21,"Male");
  User user2 = new User("Zhang SAN.", 21,"Male");
  User user3 = new User("Zhang SAN 03", 21,"Male");
  User user4 = new User("Zhang SAN 04", 21,"Male");
  userList.add(user1);
  userList.add(user2);
  userList.add(user3);
  userList.add(user4);

  System.out.println("****Java object to JSON string ****");
  String str1 = JSON.toJSONString(userList);
  System.out.println(str1);
  String str2 = JSON.toJSONString(user1);
  System.out.println(str2);

  System.out.println("****JSON string to Java object ****");
  User jp_user1 = JSON.parseObject(str2, User.class);
  System.out.println(jp_user1);

  System.out.println("****Java to JSON object ****");
  JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
  System.out.println(jsonObject1.getString("name"));

  System.out.println("****JSON to Java object ****");
  User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
  System.out.println(to_java_user);

  return "Hello";
}
Copy the code

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!