ObjectMapper

1. Rely on

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

This dependency also adds the following libraries to the project path:

  • Jackson – annotations – 2.9.8. Jar
  • Jackson – core – 2.9.8. Jar
  • Jackson — databind 2.9.8. Jar

2. serialization and deserialization

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {

    private String color;
    private String type;
}
Copy the code

2.1 Java Object serialization to Json

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Car car = new Car("yellow"."renault");
        objectMapper.writeValue(new File("target/car.json"), car); }}Copy the code

Output car. Json:

{"color":"yellow"."type":"renault"}
Copy the code

WriteValueAsString: Converts the generated JSON to a string

//{"color":"yellow","type":"renault"}
String carAsString = objectMapper.writeValueAsString(car);
Copy the code

WriteValueAsBytes: Converts the generated JSON to a byte array

2.2 JSON deserialization to Java objects

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\"}"; Car car = objectMapper.readValue(json, Car.class); System.out.println(car); }}Car(color=Black, type=BMW)
Copy the code

The readValue () function also accepts other forms of input, such as a file containing a JSON string:

 ObjectMapper objectMapper = new ObjectMapper();
        String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\"}";
        Car car = objectMapper.readValue(new File("target/json_car.json"), Car.class);
        System.out.println(car);

// Output Car(color=yellow, type= Renault)
Copy the code

Or URL

Car car = objectMapper.readValue(new URL("target/json_car.json"), Car.class);
Copy the code

2.3 JSON deserialization to Jackson JsonNode

Similarly, JSON can be parsed as a JsonNode object, fetching data from a specific node.

String json = "{ \"color\" : \"Black\", \"type\" : \"FIAT\" }";
JsonNode jsonNode = objectMapper.readTree(json);
String color = jsonNode.get("color").asText();
// Output: color -> Black
Copy the code

2.4 Deserialize JSON arrays to Java Lists

Using TypeReference, you can deserialize JSON as an array into a Java array

String jsonCarArray =
        "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, 
        { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
List<Car> listCar = objectMapper.readValue(jsonCarArray, 
    new TypeReference<List<Car>>(){});

//[Car(color=Black, type=BMW), Car(color=Red, type=FIAT)]
System.out.println(listCar);
Copy the code

2.5 Deserialize A JSON String to a Java Map

String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Map<String, Object> map
        = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
        
//{color=Black, type=BMW}        
System.out.println(map);
Copy the code

Advanced features

One of the strengths of the Jackson library is the ability to customize serialization and deserialization.

3.1 Setting serialization and deserialization features

By default, deserialization fails when the JSON string contains attributes that the Java class does not.

String jsonString
            = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";

//UnrecognizedPropertyException
Car car = objectMapper.readValue(jsonString, Car.class);
Copy the code

By setting methods we can change the default behavior to ignore the new field properties.

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonString
        = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
Car car = objectMapper.readValue(jsonString, Car.class);
//Car(color=Black, type=Fiat)
System.out.println(car);
Copy the code

FAIL_ON_NULL_FOR_PRIMITIVES: The value can be NULL.

The configuration mode is

objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
Copy the code

FAIL_ON_NUMBERS_FOR_ENUM: Controls whether enumerated values are allowed to be serialized/deserialized to numbers

The configuration mode is as follows:

objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, false)
Copy the code

See https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features for more configuration way

3.4 Processing Collections

Another small but useful feature provided by the DeserializationFeature class is the ability to generate the desired collection type from a JSON array response.

For example, we can generate the result as an array:

String jsonCarArray =
        "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
Car[] cars = objectMapper.readValue(jsonCarArray, Car[].class);
// Car(color=Black, type=BMW)
//Car(color=Red, type=FIAT)
for (Car car : cars) {
    System.out.println(car);
}
Copy the code

Or as a List:

String jsonCarArray =
        "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
// [Car(color=Black, type=BMW), Car(color=Red, type=FIAT)]
System.out.println(listCar);
Copy the code

Dealing with more data collection can be found in the https://www.baeldung.com/jackson-collection-array

4. References

  • www.baeldung.com/jackson-obj…