Java obj given JSON 互转 (jackson)

JSON parsing

Common json parser:

  • jsonlib
  • Gson (谷 歌)
  • fastjson (Ali)
  • jackson (Spring built)

jackson

Dependent jar package

  • jackson-annotations/
  • jackson-core/
  • jackson-databind/

Download the official website

1. Java objects go JSON

1.1 core object

ObjectMapper

1.2 Method of Transformation

  • WriteValue (parameter 1, obj)
  • Parameter 1:
    1. File: obj will be converted into json string and saved to the specified file
    2. Write: converting JSON string object obj, and filled into json character output data stream
    3. OutputStream: converting JSON string object obj, and filled into json data byte output stream
  • writeValueAsString (obj): converts a string JSON object obj
  • Complex objects such as List or Map convert ordinary JavaBean objects.

1.3 Common Notes

  • @JsonIgnore: Negative (plus the class attribute) property
  • @JsonFormat(pattern = "yyyy-MM-dd"): Property worth to format

2.JSON turn Java objects

method:

readValue(json字符串, obj)

3. Example

import com.fasterxml.jackson.annotation.JsonIgnore;
public class User {
    private String id;
    private String name;
    private String sex;
    private String tel;
    private String place;

    @JsonIgnore
    private String password;

    // getattr....
    // serattr....
}
package top.junebao.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import top.junebao.domain.User;

import java.io.IOException;

public class JsonTest {

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * obj对象转JSON字符串单元测试
     */
    @Test
    public void testObjToJson() {
        User user = new User();
        user.setId("LS-N4");
        user.setName("公孙胜");
        user.setPassword("gss111111");
        user.setSex("男");
        String json = "";

        try {
            json = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println(json);
    }

    /**
     * json字符串转obj单元测试
     */
    @Test
    public void testJsonToObj() {
        User user = null;
        String json = "{\"id\":\"LS-N4\",\"name\":\"公孙胜\",\"sex\":\"男\",\"tel\":null,\"place\":null}";
        try {
            user = objectMapper.readValue(json, User.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(user);
    }
}

Published 62 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/zjbyough/article/details/103810792