Java implements JSON string and object conversion
Tips before viewing:
The IDEA version used in this article is ultimate 2019.1, and the JDK version is 1.8.0_141.
1. Jackon ObjectMapper
Reference related jar packages
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
Entity Person.java
package testJsonToEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder(value = {
"ID","name","age"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
@JsonProperty("ID")
private String id;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Note :
-
@JsonPropertyOrder This annotation is used to sort properties.
-
@JsonIgnoreProperties(ignoreUnknown = true), after writing this annotation on the class, fields that do not exist in the class will be ignored.
-
@JsonProperty This annotation is used on properties, and its role is to serialize the name of the property to another name, such as serializing the trueName property to name.
-
The role of @JsonInclude(Include.NON_NULL): the field that jackson entity turns json to NULL will not participate in serialization (that is, it will not be displayed)
Test class Test.java
package testJsonToEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
private static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
Person p = new Person();
p.setId("1111");
p.setAge(18);
String jsonStr = mapper.writeValueAsString(p);
System.out.println(jsonStr);
String json = "{\"Id\":\"1111\",\"age\":18,\"sex\":\"male\"}";
Person p1 = mapper.readValue(json, Person.class);
System.out.println(p1.toString());
}
}
The result is