JSON-Initial Knowledge+Resolution

Keywords: Javascript JSON Spring MVC jackson fastjson

1. JSON

1.1 What is JSON

JSON (JavaScript Object Notation) is a lightweight data exchange format. JSON uses JavaScript syntax to describe data objects, uses a language-independent text format, and is easy to store and exchange.

The network media type of JSON is application/json.

1.2 JSON Scope of Use

JSON writes data objects based on JavaScript, so any type of JavaScript support can be represented by JSON.

JSON can be used to serialize and illustrate structured data through network connections.

Used to transfer data between Web applications.

1.3 JSO N Features

  • Stores and represents data in a text format that is completely independent of the programming language.
  • The concise and clear hierarchy makes JSON the ideal data exchange language.
  • It is easy for people to read and write shiyo, easy for machine parsing and generation, and effectively improves network transmission efficiency.

1.4 JSO N format

JSON syntax is a subset of JavaScript syntax.

  • Data is represented by key:value pairs
  • Data separated by commas
  • Use curly brackets to save objects
  • Save the array with square brackets containing multiple objects

1.5 JSON example

The format of JSON data is: name:value

  • JSON's key needs quotation marks, JavaScript doesn't need them.
  • JSON value needs quotation marks and is a string
{ "name" : "JOEL" }
{ "fly" : false }
{ "money" : null }

1.6 JSON use

Use scenarios: Response data is encapsulated in JSON format in a background application, and after being passed to the foreground page, the JSON format needs to be converted to a JavaScript object before the data can be used in the page.

2. JSON/JavaScript

Define a short answer object in JavaScript:

<script type="text/javascript">
    var user = {
        name:"Zhang San",
        age:22,
        sex:"male"
    }
</script>

2.1 Differences between JSON and JS

JSON is a string representation of a JS object. It uses text to represent information of a JS object and is essentially a string.

var obj = {a: 'Hello', b: 'World'}; //This is an object, note that key names can also be wrapped in quotes
var json = '{"a": "Hello", "b": "World"}'; //This is a JSON string, essentially a string

2.2 JS to JSON

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

// Convert JavaScript Objects to JSON
var json = JSON.stringify(user);
document.write(json);

🔵 Output: {"name": "Zhang San", "age": 22, "sex": "man"}

2.3 JSON to JS

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

// Convert JSON Objects to JavaScript
var js = JSON.parse(json);
document.write(js.name, js.age, js.sex);

🔵 Output: Zhang San22 Male

2.4 JSON interface

The method for converting JSON to and from JavaScript objects is defined in the JSON interface.

interface JSON {
    /**
     * Convert JSON Objects to JavaScript
     * @param JSON object
     * @param reviver Function that converts the result. This function will be called for each member of the object.
     * If the member contains a nested object, the nested object is converted before the parent object.
     */
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
    /**
     * Convert JavaScript Objects to JSON
     * @param value The JavaScript value to be converted is usually an object or an array.
     * @param replacer Function that converts the result.
     * @param Add indents, spaces, and line breaks to the return value JSON text to make it easier to read.
     */
    stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
    /**
     * Convert JavaScript Objects to JSON
     * @param value The JavaScript value to be converted is usually an object or an array.
     * @param An array of strings and numbers used as an approved list to select object properties that will be strings.
     * @param Add indents, spaces, and line breaks to the return value JSON text to make it easier to read.
     */
    stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}

3.JSON Parsing Tool

Parsing tools for JSON: Jackson, Fastjson

3.1 Jackson

3.1.1 What is Jackson

Jackson: An open source framework for Java that is currently widely used to serialize and deserialize json.

3.1.2 Jackson Core

Jackson has three parts: jackson-core, jackson-annotations, and jackson-databind.

jackson-core: Core package that provides related APIs based on Stream Mode parsing, including JsonPaser and JsonGenerator. The internal implementation of Jackson is to generate and parse json s through JsonGenerator and JsonParser of high performance Stream Mode APIs;

jackson-annotations: annotation packages, which provide standard annotation functions;

jackson-databind: A data binding package that provides APIs related to ObjectMapper and JsonNode resolution based on Object Binding resolution; APIs based on Object Binding resolution and tree model resolution depend on APIs based on Stream Mode resolution.

3.1.3 ObjectMapper

Jackson's most commonly used API is ObjectMapper based on Object Binding.

ObjectMapper serializes java objects into json using the writeValue series method and stores json in different formats, String (writeValueAsString), Byte Array (writeValueAsString), Writer, File, OutStream, and DataOutput.

ObjectMapper deserializes json into java objects from different data sources such as String, Byte Array, Reader, File, URL, InputStream using readValue series methods.

The writeValueAsString method is as follows:

public String writeValueAsString(Object value) throws JsonProcessingException {
    SegmentedStringWriter sw = new SegmentedStringWriter(this._jsonFactory._getBufferRecycler());

    try {
        this._writeValueAndClose(this.createGenerator((Writer)sw), value);
    } catch (JsonProcessingException var4) {
        throw var4;
    } catch (IOException var5) {
        throw JsonMappingException.fromUnexpectedIOE(var5);
    }

    return sw.getAndClear();
}

3.2 Fastjson

3.2.1 What is Fastjson

fastjson is Alibaba's open source JSON parsing library that parses strings in JSON format, supports serialization of Java Bean s to JSON strings, and can also deserialize from JSON strings to JavaBean s.

Features: fast, widely used, complete testing, simple use, complete function.

3.2.2 Fastjson class

FastJson parses JSON format strings in three main classes: JSON, JSONObject, and JSONArray.

  • A parser for JSON:fastJson used to convert JSON format strings to and from JSON objects and javaBean s.
  • JSONObject: The json object provided by fastJson.
  • JSONArray: fastJson provides a json array object.

public abstract class JSON implements JSONStreamAware, JSONAware {...}
public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler {...}
public class JSONArray extends JSON implements List<Object>, Cloneable, RandomAccess, Serializable {...}

4. SpringMVC-JSON

4.1 Jackson style

4.1.1 Import Dependency

Import jackson-databind dependencies in pom.xml.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

4.1.2 Writing POJO

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
}

4.1.3 Output Object

4.1.3.1 Writing Controller

Parsing steps:

1️⃣ Step1: Instantiate ObjectMapper object

2️⃣ Step2: Instantiate the User object

3️⃣ Step3: Parse POJO into JOSN format using the writeValueAsString method and return String

@RestController
public class UserController {

    //@ResponseBody
    @RequestMapping(value = "/Json")
    public String test() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User(1, "Zhang San", "123123");
        String str = objectMapper.writeValueAsString(user);
        return str;
    }
}

@RestController: This is also a Controller, and the comment indicates that you don't need to walk the View anymore

Interpretation: Previously, methods in Controller returned view names of type String, but now we need to return JSON. In order not to modify the view parser, we can apply this annotation on the class so that we don't go through the view anymore.

🌈 The URL is the value of @RequestMapping.

@ResponseBody: Comments indicating method return values should be bound to the web response body. Processor methods with comments are supported.

This annotation implements that you don't have to go through the view anymore.

🌈 @The RestController comment is actually labeled by @ResponseBody!

4.1.3.1 Test Output

4.1.4 Output Set

4.1.4.1 Writing Controller

@RestController
public class UserController {

    @RequestMapping(value = "/JsonList")
    public String test2() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User(1, "Zhang San", "123123");
        User user2 = new User(1, "Li Si", "123123");
        List<User> list = new ArrayList<>();
        list.add(user);
        list.add(user2);
        String str = objectMapper.writeValueAsString(list);
        return str;
    }
}

4.1.4.2 Test Output

4.1.5 Output Date

4.1.5.1 Writing UTILS

Ideas:

1️⃣ Step1: Instantiate ObjectMapper object

2️⃣ Step2: Instantiate the SimpleDateFormat object, passing in the date format

3️⃣ Step3: Specify the format for the ObjectMapper object through the setDateFormat method

4️⃣ Step4: Convert the date to JSON data and output the string using the writeValueAsString method

5️⃣ Step5: Overload method, specify a default date format

public class JsonDateUtils {

    public static String getJsonDate(Object object){
        return getJsonDate(object, "yyyy-MM-dd HH:mm:ss")
    }

    /**
     * format date
     * @param object date
     * @param dateFormat Custom date format
     * @return Return date string
     */
    public static String getJsonDate(Object object, String dateFormat) {

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        objectMapper.setDateFormat(sdf);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

4.1.5.2 Writing Conreoller

@RestController
public class UserController {

    @RequestMapping("/JsonDate")
    public String getDate(){
        return JsonDateUtils.getJsonDate(new Date());
    }
}

4.1.5.3 Test Output

4.2 Fastjson

4.2.1 Import Dependency

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

4.2.2 Writing test classes

public class FastJsonTest {

    public static void main(String[] args) {
        User user1 = new User(1,"Zhang San","123123");
        User user2 = new User(2,"Li Si","123123");
        User user3 = new User(3,"King Five","123123");
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
    }
}

4.2.3.1 JAVA to JSON

System.out.println("===Java Object to JSON Character string===");
System.out.println("userJSON: " + JSON.toJSONString(user1));
System.out.println("listJSON: " + JSON.toJSONString(list));

/*
Output:
===Java Object to JSON string===
userJSON: {"id":1,"name":"Zhang San ","password":"123123 "}
listJSON: [{"id":1,"name":"Zhang San ","password ":" 123123 "}, {ID": 2,"name":"Li Si", "password":"123123"}, {ID ": 3," name ":" Wang Wu ","password ":" 123123 "}]
*/

4.2.3.2 JSON to JAVA

System.out.println("===JSON String to Java object===");
System.out.println("user: " + JSON.parseObject(JSON.toJSONString(user1), User.class));
System.out.println("list: " + JSON.parseObject(JSON.toJSONString(list), List.class));

/*
Output:
===JSON String to Java Object===
user: User(id=1, name=Zhang San, password=123123)
list: [{"password":"123123","name":"Zhang San ","id":1}, {"password":"123123","name":"Li Si","id":2}, {"password":"123123","name":"Wang Wu","id":3}]
*/

5. Write at the end

The common parser for JSON is Goole's gson, but it is slower.

 

❤️ END ❤️

Posted by terfle on Thu, 14 Oct 2021 09:51:14 -0700