Detailed use of Java-Jackson

 
 

Detailed use of Java-Jackson

Serialization

What is Json?

1. Basic rules

2. Get data

3. Purpose

Jackson

1. Import the Jar package

2.Json annotation

3.Json converted to Java object

4. Java Object Conversion Json


Serialization

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

What is Json?

Jason is JavaScript Object Notation—JavaScript object notation, which is a lightweight data exchange format. It is mainly used for data transmission. For example, if you write a Java object 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

  The data is in name/value pairs: json data is composed of key-value pairs

     Enclose the value in quotation marks or not

     Value type: number, string, boolean, array (such as {"persons":[{},{},{}]}), object, null

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

     Square brackets save the array: []

     Curly braces to save the object: use {} to define the json format

2. Get data

    json object. key name

    json object["key name"]

    Array object [index]

    Traverse

3. Purpose

   Make the custom object persistent in some storage form;

   Pass objects from one place to another.

   Make the program more maintainable.


Jackson

There are many libraries in the Java ecosystem that handle JSON and XML formatting, common parsers: Jsonlib, Gson, fastjson, Jackson. Jackson is one of the more famous and convenient. , Jackson is relatively efficient. Jackson is mainly used in the project to convert between JSON and Java objects. Here are some Jackson JSON operation methods.

1. Import the Jar package

2.Json annotation

@JsonIgnore This annotation is used for attributes, and the function is to ignore the attribute when performing JSON operations.

@JsonFormat This annotation is used on attributes. The function is to directly convert the Date type into the desired format, such as @JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss").

@JsonProperty This annotation is used on properties, and the role is to serialize the name of the property to another name, such as serializing the trueName property to name, @JsonProperty("name").

public class Person {

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

   // @JsonIgnore//忽略该属性,不进行转换
    @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.Json converted to Java object

Import the relevant jar packages of Jackson

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)

//将Json字符串转为Java对象
    @Test
    public  void  test5() throws Exception{
        //json字符串
        String str="{\"gender\":\"男\",\"name\":\"zhangsan\",\"age\":23}";
        //Jackson核心对象
        ObjectMapper mapper = new ObjectMapper();
        //使用readValue方法进行转换
        Person person = mapper.readValue(str, Person.class);
        System.out.println(person);
    }

4. Java Object Conversion Json

Import the relevant jar packages of Jackson

Create Jackson's core object, ObjectMapper

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

        writeValue(parameter, obj object)

               Parameters: File: Convert the obj object into a JSON string and save it to the specified file

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

               Parameters: OutputStream: Convert obj object into JSON string, and fill json data into byte output stream

        writeValueAsString(obj): Convert the object to a json string (commonly used)

 //Java对象转Json
    @Test
    public void test1() throws IOException {

        //1.创建Java对象
        Person p=new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");

        //2.创建Jackson对象 ObjectMapper
        ObjectMapper mapper=new ObjectMapper();
        //3.转换为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.创建Java对象
        Person p = new Person();
        p.setName("张三");
        p.setAge(23);
        p.setGender("男");
        p.setBirthday(new Date());
        //2.创建Jackson对象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3.转换为JSOn
        String json = mapper.writeValueAsString(p);
        System.out.println(json);
    }


    @Test
    public void test3() throws Exception {
        //复杂格式的转换:list
        //1.创建Java对象
        Person p1 = new Person();
        p1.setName("张三");
        p1.setAge(23);
        p1.setGender("男");
        p1.setBirthday(new Date());

        Person p2 = new Person();
        p2.setName("张三");
        p2.setAge(23);
        p2.setGender("男");
        p2.setBirthday(new Date());

        List<Person> list=new ArrayList<>();
        list.add(p1);
        list.add(p1);
   
        //2.创建Jackson对象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3.转换为JSOn
        String json = mapper.writeValueAsString(list);
        System.out.println(json);//[{"name":"张三","age":23,"gender":"男","birthday":"2021-03-19"},{"name":"张三","age":23,"gender":"男","birthday":"2021-03-19"}]

    }

    @Test
    public  void   test4() throws Exception{
        //复杂格式的转换Map
        //1.创建map对象
        Map<String,Object> map=new HashMap<>();
        map.put("name","zhangsan");
        map.put("age",23);
        map.put("gender","男");
        //2.创建Jackson对象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3.转换为JSOn
        String json = mapper.writeValueAsString(map);
        System.out.println(json);//{"gender":"男","name":"zhangsan","age":23}
    }

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

 

 

Guess you like

Origin blog.csdn.net/promsing/article/details/114986873