1. Introduction to JSON

Person p = new Person(); P. etName (" * * "); p.setAge(23); P. etGender (" male "); Var p = {"name":" zhang SAN ","age":23,"gender":" male "}; * JSON is now mostly used as a syntax for storing and exchanging text information * for data transfer * JSON is smaller, faster, and easier to parse than XML.Copy the code

2. The json syntax

1. Basic rule * Data is in name/value pairs: JSON data is made up of key-value pairs * the keys are quoted (even or odd), or they are not quoted * Worthwhile values: 1. Number (integer or floating point) 2. String (in double quotation marks) 3. Logical value (true or false) 4. {"persons":[{},{}]} 5. Object (in curly braces) {"address":{"province" : "shaanxi ".... }} 6. null * Data separated by commas: Multiple key-value pairs separated by commas * Curly braces hold objects: use {} to define JSON format * Square brackets hold arrays: [] 2. Obtain data: 1. Json object. Json object [" key "] 3. Array object [index] 4. Var person = {"name": "zhang SAN ", age: 23, 'gender': true}; Var ps = [{" name ":" zhang ", "age" : 23, "gender" : true}, {" name ":" bill ", "age" : 24, "gender" : true}, {" name ":" detective ", "age" : 25, "gender": false}]; //for in loop /* for(var key in person){// Get all the keys in the person object. "Name" //alert(key + ":" + person.key); alert(key+":"+person[key]); } for (var I = 0; i < ps.length; i++) { var p = ps[i]; for(var key in p){ alert(key+":"+p[key]); }}Copy the code

Convert JSON data to Java objects

JSON parsers: * Common parsers: Jsonlib, Gson, Fastjson, Jackson 1. JSON to Java objects 1. Import jar packages related to Jackson. 2. Create a Jackson core object ObjectMapper. 1. ReadValue (JSON string data,Class) 2. Java object conversion JSON 1. Import jar packages related to Jackson. 2. Create ObjectMapper for Jackson. 3. * writeValue(parameter 1, obj): Parameter 1: File: Converts an obj object to a JSON string and saves it to the specified File Writer: converts an OBj object to a JSON string and populates the JSON data into an OutputStream: Convert an obj object to a JSON string and populate the JSON data into a byte output stream * writeValueAsString(obj): Convert an object to a JSON string 2. Note: 1. @jsonignore: Excludes attributes. @jsonFormat: Attribute worth formatting * @jsonFormat (pattern = "YYYY-MM-DD ") 3. Complex Java object conversion 1. List: array 2. Map: object format consistencyCopy the code

Sample code:

Java objects are converted to JSON strings

package com.baoji.web.test; import com.baoji.web.entity.Person; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.File; import java.io.FileWriter; import java.util.*; Public class JacksonTest {//1, import Jackson related jar package (web-INF lib) // Java object to json string @test public voidtest() throws Exception {//2, create a Person object Person = new Person(); person.setName("Zhang");
        person.setAge(20);
        person.setGender("Male"); Sackson ObjectMapper ObjectMapper = new ObjectMapper(); /* Convert method writeValue(parameter 1, obj) : parameter 1: file: Writer: convert an obj object to a json string and fill it with json data into a character OutputStream. And to fill the json data into the output byte stream writeValueAsString (obj) : converts the object to a json String * / String json = objectMapper. WriteValueAsString (person); / / {"name":"Zhang"."age": 20."gender"."Male"} //System.out.println(json); //a.txt File objectMapper.writeValue(new File("I://a.txt"),person); // objectMapper.writeValue(new FileWriter("I://b.txt"),person);
    }
Copy the code

Use annotations to format the JSON format

@test /* Using JsonIgnore annotations: Ignore attributes to json string JsonFormat(pattern ="yyyy-MM-dd"Note: Formatting to JSON ({"name":"Bill"."age": 21."gender":"Female"."birthday":"2019-10-31"})
     */

    public void testThrows Exception {//1, create a Person object Person p = new Person(); p.setName("Bill");
        p.setAge(21);
        p.setGender("Female"); p.setBirthday(new Date()); Sackson ObjectMapper mapper = new ObjectMapper(); / / 3, converts the object to a json String String json = mapper. WriteValueAsString (p); System.out.println(json); / / {"name":"Bill"."age": 21."gender":"Female"."birthday":1572521699055}
    }
Copy the code

Collection objects are converted to JSON strings

/* List: array [{"name":"Bill"."age": 21."gender":"Female"."birthday":"2019-10-31"}, {"name":"Zhang"."age": 21."gender":"Male"."birthday":"2019-10-31"}, {"name":"Fifty"."age": 21."gender":"Male"."birthday":"2019-10-31"}] Map: object format consistent {"gender":"Male"."name":"Zhang"."age":20} */ //List to json string @test public voidtestThrows Exception {//1, create a Person object Person p = new Person(); p.setName("Bill");
        p.setAge(21);
        p.setGender("Female");
        p.setBirthday(new Date());

        Person p1 = new Person();
        p1.setName("Zhang");
        p1.setAge(21);
        p1.setGender("Male");
        p1.setBirthday(new Date());

        Person p2 = new Person();
        p2.setName("Fifty");
        p2.setAge(21);
        p2.setGender("Male"); p2.setBirthday(new Date()); List<Object> List = new ArrayList<Object>(); list.add(p); list.add(p1); list.add(p2); Sackson ObjectMapper mapper = new ObjectMapper(); / / 3, converts the object to a json String String json = mapper. WriteValueAsString (list); System.out.println(json); / /}Copy the code

The Map collection is converted to a string

//Map collection to json string @test public voidtest4() throws Exception {// Create a Map collection Object Map<String,Object> Map = new HashMap<String,Object>(); map.put("name"."Zhang");
        map.put("age", 20); map.put("gender"."Male"); Sackson ObjectMapper mapper = new ObjectMapper(); / / 3, converts the object to a json String String json = mapper. WriteValueAsString (map); System.out.println(json); / / {"name":"Bill"."age": 21."gender":"Female"."birthday":1572521699055}
    }

Copy the code

Case study:

* Verify whether the user name exists. 1. The data that the server responds to must be used as JSON data on the client. There are two solutions: 1. $.get(type): specify the last parameter type as "json" 2. Set the MIME type response.setContentType("application/json; charset=utf-8");Copy the code

To be continued…

Write in the last

The recommended author’s Github address is github.com/Lmobject