preface

  • 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 of JSON key-value pairs. This is a way to hold JavaScript objects. JavaScript objects are also written in similar ways: The key/value pair pairs are preceded by the key name and enclosed by double quotation marks (“), separated by colons (:), followed by the value:
{"name": "xiaotang"} {"age": "18"}Copy the code

Many people don’t understand the relationship between JSON and JavaScript objects, or even who is who. In fact, it can be understood as follows:

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'}; Var json = '{"a": "Hello", "b": "World"}'; // This is a JSON string, essentially a stringCopy the code

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

var obj = JSON.parse('{"a": "Hello", "b": "World"}'); {a: 'Hello', b: 'World'}Copy the code

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

var json = JSON.stringify({a: 'Hello', b: 'World'}); {"a": "Hello", "b": "World"}'Copy the code

The test case

The front-end interface displays JSON data

1. Create a SpringBoot project. 2. Create a JSON-1. HTML file in the template engine directory and write the test content

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script Type ="text/javascript"> // write a js object var user = {name:" yfei-long ", age:3, sex:" male "}; Var STR = json.stringify (user); console.log(str); Parse (STR); // Convert json string to js object var user2 = json.parse (STR); console.log(user2.age,user2.name,user2.sex); </script> </body> </html>Copy the code

3. Open the IDEA in a browser 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;

SpringBoot does not have to introduce dependencies to show that tomacat cannot be opened with major jar package conflicts

So we’re going to need two new things here, an @ResponseBody and an ObjectMapper object, so let’s see how we can use it 1. Write an entity class for User, and then we write our test Controller;

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 + '\'' + '}'; }}Copy the code

2. Write a Controller

import com.example.demojson.pojo.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; Public class UserController {@requestMapping ("/json1") @responseBody public String Json1 () throws JsonProcessingException {// create a Jackson ObjectMapper to parse data ObjectMapper mapper = new ObjectMapper(); // create an object User User = new User(" Yin Fei long ", 18, "male "); / / will be our object parsing json format String STR = mapper. WriteValueAsString (user); // Because of the @responseBody annotation, the STR is returned as json; Return STR; }}Copy the code

3. Output results:

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 end separation development, which is very convenient.

Test set output

@requestMapping ("/json2") Public String json2() throws JsonProcessingException {// Create a Jackson object mapper, ObjectMapper mapper = new ObjectMapper(); // create an object User user1 = new User(" yingfeilong1 ", 18, "male "); User user2 = new User(" user2 ", 18, "male "); User user3 = new User(" user3 ", 19, "male "); User user4 = new User(" user4 ", 20, "male "); 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; }Copy the code

Output time object

@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

Output result:

  • Specific information about the number displayed

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

  • Jackson defaults to timestamps

    Solution: Cancel the timestamps form and customize the time format

@RequestMapping("/json4") @ResponseBody public String json4() throws JsonProcessingException { ObjectMapper mapper = new  ObjectMapper(); / / do not use the timestamp mapper. The configure (SerializationFeature WRITE_DATES_AS_TIMESTAMPS, false); SimpleDateFormat SDF = new SimpleDateFormat(" YYYY-MM-DD HH: MM :ss"); // Specify the date format mapper.setDateformat (SDF); Date date = new Date(); String str = mapper.writeValueAsString(date); return str; }Copy the code

Time display successful

Extract as a utility class

Create an Util package to store some utility classes to reduce code complexity and duplication

package com.example.demojson.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); SimpleDateFormat SDF = new SimpleDateFormat(dateFormat); // Specify the date format mapper.setDateformat (SDF); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; }}Copy the code

Test code: Same effect great simplification

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

Copy the code

Output result:

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!