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

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

com.fasterxml.jackson.core jackson-databind 2.9.8 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 of Jackson as much as possible With the deserialization function, the array, List, and Map are all integrated into this class. And initialize the basketball star Jordan object through getInstance.

@Data
public class PlayerStar {

private String name;
private Integer age;
private String[] hobbies; //Hobbies, array
private List friends; // Friends
private Map<String, BigDecimal> salary; //Annual income Map

//Initialize an object for testing
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;

}

}
2. 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 the file.
writeValueAsString returns the JSON serialization result as a String. The
writerWithDefaultPrettyPrinter method can format the JSON serialization result, better display structure, and easy to view
@Test
void testObject2JSON () throws IOException { //Get object instance PlayerStar player = PlayerStar.getInstance();

//ObjectMapper exists as Jackson’s API tool class.
ObjectMapper mapper = new ObjectMapper();
//Serialize the player object in JSON format, and write the serialization result to the file
mapper.writeValue(new File("d:\data \jackson\player.json”), player);

//Serialize the player object into a String object in JSON format
String jsonString = mapper.writeValueAsString(player);
System.out.println(jsonString);

//Serialize the player object into a String object in JSON format (format beautification)
String jsonInString2 = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(player);
System.out.println(jsonInString2);
}
jsonString console print output result, Also the content of the d:\data\jackson\player.json file

{"Name":"Jordan","age":45,"hobbies":["golf","baseball"],"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": "Jordan", "age": 45, "hobbies": ["golf", "baseball" ], "friends": ["kobe", "curry", "james" ], "salary ": { "2000": 10000000, "2010": 62000000, "2020": 112400000 } } 3. 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(); //Read the JSON string from the file and deserialize it into a java object PlayerStar player = mapper.readValue(new File("d:\data\ jackson\player.json”), PlayerStar.class); System.out.println(player);



//Deserialize the JSON string into a java object
String jsonInString = "{"name":"Jordan","age":45,"hobbies":["golf","baseball"]}";
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=Jordan, age=45, hobbies=[golf, baseball], friends=[kobe, curry, james], salary={2000=10000000, 2010=62000000, 2020=112400000})
PlayerStar(name=Jordan , age=45, hobbies=[golf, baseball], friends=null, salary=null)
Fourth, field renaming @JsonProperty
can use @JsonProperty to affect the renaming of serialized and deserialized object properties.

@Data
public class PlayerStar {

@JsonProperty("playerName")
private String name; //Serialize the property name to playerName, which also affects deserialization. After
using the annotations in the above code, the name property of the result of JSON serialization becomes the playerName property

{"PlayerName":"Jordan" ……It
also affects deserialization. The following deserialization code will report an error because the name attribute is used. PlayerName should be used.

String jsonInString = "{"name":"Jordan","age":45,"hobbies":["golf","baseball"]}";
PlayerStar jordan = mapper.readValue(jsonInString, PlayerStar.class);
5. Ignore the serialization of null fields @JsonInclude
When we do not assign values ​​to the member variables of the object, by default, Jackson's serialization results are as follows.

{ "Age": 45, "hobbies": null, "friends": null, "salary": null, "playerName": "Jordan" } If we do not want the null value to be reflected in the JSON serialization result, we The following methods can be used. 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 for some member variables in the PlayerStar class, we can add annotations to the member variables.


@JsonInclude(JsonInclude.Include.NON_NULL)
private String[] hobbies; //Hobbies, array
@JsonInclude(JsonInclude.Include.NON_NULL)
private List friends; // friends
@JsonInclude(JsonInclude.Include.NON_NULL)
private Map<String , BigDecimal> salary; //After the annual income Map
ignores the null member variable, the JSON serialization result is as follows

{ "Age": 45, "playerName": "Jordan" } Six. Ignore the specified fields By default, Jackson will not serialize and deserialize static and transient member variables. We can also pass




@JsonIgnore is added to the class member variable, the member variable will be excluded from the serialization and deserialization process
@JsonIgnoreProperties is added to the class declaration to specify which fields in the class are excluded from serialization and deserialization Outside the process,
you can choose one of the two annotations above. I have used both annotations in the code below, and the function is repeated

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

@JsonProperty(“playerName”)
private String name;
private Integer age;

@JsonIgnore
private String[] hobbies; //Hobbies, array
@JsonIgnore
private List friends; // Friends
@JsonIgnore
private Map<String, BigDecimal> salary; //Annual income Map


After adding annotations to the class or member variable, the serialization result is as follows, and the specified field is ignored.

{ "Age": 45, "playerName": "Jordan" } It should be noted that these two annotations not only affect the process of serializing to JSON string, but also the process of deserializing JSON string to java object. 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. Shenzhen website construction www.sz886.com




Guess you like

Origin blog.csdn.net/weixin_45032957/article/details/108637147