Detailed explanation of Java Jackson

Posted by Daniel Mott on Sun, 20 Feb 2022 07:08:49 +0100

If you are Xiaobai, this set of information can help you become a big bull. If you have rich development experience, this set of information can help you break through the bottleneck
2022web full set of video tutorial front-end architecture H5 vue node applet Video + data + code + interview questions.

Detailed explanation of Java Jackson

serialize

What's Jason?

1. Basic rules

2. Obtain data

3. Purpose

Jackson

1. Import Jar package

2. Jason notes

3. Convert JSON to Java object

4.Java object conversion Json

serialize

Serialization is the process of converting the state information of an object into a form that can be stored or transmitted. During serialization, an object writes its current state to a temporary or persistent store. Later, you can recreate the object by reading or deserializing its state from the store.

What's Jason?

Jason is a JavaScript Object Notation, a lightweight data exchange format. It is mainly used for data transmission. For example, a Java object is written on the back end. If you want to use this object in other places (front end), you need to convert it to Json for transmission.

1. Basic rules

Data in name / value pairs: json data consists of key value pairs

Values are enclosed in quotation marks or not

Value types: number, string, Boolean, array (such as {"people": [{}, {}, {}]}), object, null

Data is separated by commas: multiple key value pairs are separated by commas

Square bracket save array: []

Curly brace save object: use {} to define json format

2. Obtain data

json object Key name

json object ["key name"]

Array object [index]

ergodic

3. Purpose

Persistence of custom objects in some form of storage;

Transfer objects from one place to another.

Make the program more maintainable.

Jackson

There are many class libraries dealing with JSON and XML formatting in the Java ecosystem, and common parsers are Jsonlib, Gson, fastjson and Jackson. Jackson is one of the more famous and convenient ones., Jackson is relatively efficient. Jackson is mainly used for JSON and Java object conversion in the project. Some JSON operation methods of Jackson are given below.

1. Import Jar package

2. Jason notes

@JsonIgnore this annotation is used on the attribute to ignore the attribute during JSON operation.

@JsonFormat this annotation is used on attributes to directly convert the Date type to the desired format, such as @ JsonFormat(pattern = "yyyy MM DD HH mm SS").

@JsonProperty this annotation is used on a property to serialize the name of the property into another name. For example, serialize the trueName property into name, @ JsonProperty("name").

public class Person {

    private String name;
    private int age;
     @JsonProperty("gender")
    private String gender;

   // @JsonIgnore / / ignore this attribute and do not convert
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", gender='" + gender + ''' +
                '}';
    }
}

3. Convert JSON to Java object

Import Jackson's related jar package

Create Jackson's core object, ObjectMapper

Call the relevant methods of ObjectMapper for data conversion -- convert the Json string into a Java object

readValue(json string data, class. Class)

//Convert Json string to Java object
    @Test
    public  void  test5() throws Exception{
        //json string
        String str="{"gender":"male","name":"zhangsan","age":23}";
        //Jackson core object
        ObjectMapper mapper = new ObjectMapper();
        //Use the readValue method for conversion
        Person person = mapper.readValue(str, Person.class);
        System.out.println(person);
    }

4.Java object conversion Json

Import Jackson's related jar package

Create Jackson's core object, ObjectMapper

Call relevant methods of ObjectMapper for data conversion -- convert Java objects to Json

Writevalue (parameter, obj object)

Parameter: File: convert obj object into JSON string and save it to the specified file

Parameter: Writer: convert obj object into JSON string, and fill JSON data into character output stream

Parameter: OutputStream: convert obj object into JSON string, and fill JSON data into byte output stream

writeValueAsString(obj): convert object to json string (common)

 //Java object to Json
    @Test
    public void test1() throws IOException {

        //1. Create Java objects
        Person p=new Person();
        p.setName("Zhang San");
        p.setAge(23);
        p.setGender("male");

        //2. Create Jackson ObjectMapper
        ObjectMapper mapper=new ObjectMapper();
        //3. Convert to JSOn
        String json = mapper.writeValueAsString(p);
        System.out.println(json);
        mapper.writeValue(new File("d:\jaon.txt"),json);
        mapper.writeValue(new FileWriter("d:\json.txt"),json);
    }


    @Test
    public void test2() throws JsonProcessingException {

        //1. Create Java objects
        Person p = new Person();
        p.setName("Zhang San");
        p.setAge(23);
        p.setGender("male");
        p.setBirthday(new Date());
        //2. Create Jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3. Convert to JSOn
        String json = mapper.writeValueAsString(p);
        System.out.println(json);
    }


    @Test
    public void test3() throws Exception {
        //Conversion of complex format: list
        //1. Create Java objects
        Person p1 = new Person();
        p1.setName("Zhang San");
        p1.setAge(23);
        p1.setGender("male");
        p1.setBirthday(new Date());

        Person p2 = new Person();
        p2.setName("Zhang San");
        p2.setAge(23);
        p2.setGender("male");
        p2.setBirthday(new Date());

        List<Person> list=new ArrayList<>();
        list.add(p1);
        list.add(p1);
   
        //2. Create Jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3. Convert to JSOn
        String json = mapper.writeValueAsString(list);
        System.out.println(json);//[{"name": "Zhang San", "age":23,"gender": "male", "birthday":"2021-03-19"},{"name": "Zhang San", "age":23,"gender": "male", "birthday":"2021-03-19"}]

    }

    @Test
    public  void   test4() throws Exception{
        //Complex format conversion Map
        //1. Create a map object
        Map<String,Object> map=new HashMap<>();
        map.put("name","zhangsan");
        map.put("age",23);
        map.put("gender","male");
        //2. Create Jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3. Convert to JSOn
        String json = mapper.writeValueAsString(map);
        System.out.println(json);//{"gender": "male", "name":"zhangsan","age":23}
    }

It's not easy to create. If this blog is helpful to you, please remember to leave a message + like it.

Topics: Javascript Front-end html