JSON data processing framework Jackson explained the first part-serialization and deserialization core usage

Jackson is the default JSON data processing framework of Spring Boot, but it does not depend on any Spring library. Some friends think that Jackson can only be used in the Spring framework, but it is not. There is no such restriction. It provides many JSON data processing methods and annotations , as well as functions such as streaming API, tree model, data binding , and complex data type conversion. Although it is simple and easy to use, it is definitely not a small toy. This section introduces you to the basic core usage of Jackson. I will write a series of 5-10 articles for more content. Please continue to pay attention to me.

1. Basic preparation

Introducing the following jar into any project can use jackson to perform JSON data serialization and deserialization.

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

Write a PlayerStar entity class. The entity class mainly reflects the name, age, hobbies, friends, annual income and other information of the basketball star. In order to demonstrate the serialization and deserialization functions of Jackson as much as possible, the array, List, and Map are all Integrated into this class. And initialize the object of basketball star Jordan through getInstance.

@Data
public class PlayerStar {

  private String name;
  private Integer age;
  private String[] hobbies;    //业余爱好,数组
  private List<String> friends;   //  朋友
  private Map<String, BigDecimal> salary; //年收入 Map


  //初始化一个对象用于测试
  public static PlayerStar getInstance(){
    PlayerStar playerStar = new PlayerStar();

    playerStar.setName("乔丹");
    playerStar.setAge(45);
    playerStar.setHobbies(new String[]{"高尔夫球", "棒球"});
    Map<String, BigDecimal> salary = new HashMap<String, BigDecimal>() {
   
   {
      put("2000", new BigDecimal(10000000));
      put("2010", new BigDecimal(62000000));
      put("2020", new BigDecimal(112400000));
    }};
    playerStar.setSalary(salary);
    playerStar.setFriends(Arrays.asList("kobe", "curry", "james"));

    return playerStar;
  }

}

Two, serialization method

The following code demonstrates how to serialize the PlayerStar object into a JSON string.

  • writeValue can receive File as a parameter and save the JSON serialization result to a file
  • writeValueAsString returns the JSON serialization result in String form
  • The writerWithDefaultPrettyPrinter method can format the JSON serialization result, which has a better display structure and is easy to view
@Test
void testObject2JSON() throws IOException {
  //获取对象实例
  PlayerStar player = PlayerStar.getInstance();

  //ObjectMapper作为Jackson的API工具类存在
  ObjectMapper mapper = new ObjectMapper();
  //将player对象以JSON格式进行序列化,并将序列化结果写入文件
  mapper.writeValue(new File("d:\\data\\jackson\\player.json"), player);

  //将player对象以JSON格式进行序列化为String对象
  String jsonString = mapper.writeValueAsString(player);
  System.out.println(jsonString);

  //将player对象以JSON格式进行序列化为String对象(格式美化)
  String jsonInString2 = mapper.writerWithDefaultPrettyPrinter()
          .writeValueAsString(player);
  System.out.println(jsonInString2);
}

The console print output of jsonString is also the content of the d:\data\jackson\player.json file


{"name":"乔丹","age":45,"hobbies":["高尔夫球","棒球"],"friends":["kobe","curry","james"],"salary":{"2000":10000000,"2010":62000000,"2020":112400000}}

The console print output of jsonString2, the format is beautified, because the writerWithDefaultPrettyPrinter() method is used

{
  "name" : "乔丹",
  "age" : 45,
  "hobbies" : [ "高尔夫球", "棒球" ],
  "friends" : [ "kobe", "curry", "james" ],
  "salary" : {
    "2000" : 10000000,
    "2010" : 62000000,
    "2020" : 112400000
  }
}

Three, deserialization method

The following code demonstrates how to deserialize a JSON string into a Java object

@Test
void testJSON2Object() throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  //从文件中读取JSON字符串,反序列化为java对象
  PlayerStar player = mapper.readValue(new File("d:\\data\\jackson\\player.json"), PlayerStar.class);
  System.out.println(player);

  //将JSON字符串反序列化为java对象
  String jsonInString = "{\"name\":\"乔丹\",\"age\":45,\"hobbies\":[\"高尔夫球\",\"棒球\"]}";
  PlayerStar jordan = mapper.readValue(jsonInString, PlayerStar.class);

  System.out.println(jordan);

}

The console output of the PlayerStar object is as follows ( note that the output here is not in JSON format, but the value of the toString() method of the java object ):

PlayerStar(name=乔丹, age=45, hobbies=[高尔夫球, 棒球], friends=[kobe, curry, james], salary={2000=10000000, 2010=62000000, 2020=112400000})
PlayerStar(name=乔丹, age=45, hobbies=[高尔夫球, 棒球], friends=null, salary=null)

Four, field renaming@JsonProperty

You can use @JsonProperty to influence the renaming of serialized and deserialized object properties.

@Data
public class PlayerStar {

  @JsonProperty("playerName")
  private String name;  //将属性name序列化为playerName,同时影响反序列化

After using the annotation of the above code, the name attribute of the result of JSON serialization becomes the playerName attribute

{"playerName":"乔丹"  ……

At the same time, it affects deserialization. The following deserialization code will report an error because the name attribute is used. PlayerName should be used.

String jsonInString = "{\"name\":\"乔丹\",\"age\":45,\"hobbies\":[\"高尔夫球\",\"棒球\"]}";
PlayerStar jordan = mapper.readValue(jsonInString, PlayerStar.class);

Five, ignore the serialization of null fields@JsonInclude

When we don't assign values ​​to the member variables of the object, by default, Jackson's serialization result is as follows.

{
  "age" : 45,
  "hobbies" : null,
  "friends" : null,
  "salary" : null,
  "playerName" : "乔丹"
}

If we do not want the null value to be reflected in the JSON serialization result, we can use the following method. If you want to ignore the null member variable in the global scope of a certain serialization, you can use the following API

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Or add the following comment above the class name. This annotation will take effect for all member variables in the class. As long as the member variable is null, it will not be included in the serialization result.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class PlayerStar {
   ......
}

If we want to ignore null separately for certain member variables in the PlayerStar class, we can add annotations to the member variables.

@JsonInclude(JsonInclude.Include.NON_NULL)
private String[] hobbies;    //业余爱好,数组
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<String> friends;   //  朋友
@JsonInclude(JsonInclude.Include.NON_NULL)
private Map<String, BigDecimal> salary; //年收入 Map

After ignoring the null member variables, the JSON serialization result is as follows

{
  "age" : 45,
  "playerName" : "乔丹"
}

Six, ignore the specified field

By default, Jackson will not serialize and deserialize static and transient member variables. We can also pass

  • @JsonIgnoreAdded to the class member variable, the member variable will be excluded from the serialization and deserialization process
  • @JsonIgnorePropertiesAdd to the class declaration to specify which fields in the class are excluded from the serialization and deserialization process

You can choose one of the two annotations above. I have used both annotations in the code below, and the functions are repeated

@Data
@JsonIgnoreProperties({"hobbies", "friends","salary"})
public class PlayerStar {

  @JsonProperty("playerName")
  private String name;
  private Integer age;

  @JsonIgnore
  private String[] hobbies;    //业余爱好,数组
  @JsonIgnore
  private List<String> friends;   //  朋友
  @JsonIgnore
  private Map<String, BigDecimal> salary; //年收入 Map

......

After adding annotations to the class or member variables, the serialization results are as follows, and the specified fields are ignored.

{
  "age" : 45,
  "playerName" : "乔丹"
}

It should be noted that these two annotations not only affect the process of serializing into JSON strings, but also the process of deserializing JSON strings into java objects. Example: If the JSON string contains the attribute value hobbies of JsonIgnore in the class, it will not be deserialized and assigned to the member variable hobbies of the java object.

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/108634752