Java PropertyMetadata-class And Method Code Example


The PropertyMetadata class from the com.fasterxml.jackson.databind package is used to store metadata about a property of a Java object. This class is typically used internally by the ObjectMapper class, rather than being used directly by application code.

Here is an example of how to use the PropertyMetadata class with the ObjectMapper class to customize the serialization of a Java object:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class MyClass {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        MyObject obj = new MyObject();
        obj.setName("John");
        obj.setAge(30);

        String json = mapper.writeValueAsString(obj);
        System.out.println(json);
    }
}

class MyObject {
    private String name;
    private int age;

    @JsonProperty(value = "name", required = true)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty(value = "age", access = JsonProperty.Access.READ_ONLY)
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

In this example, the @JsonProperty annotation is used to customize the serialization of the name and age properties of the MyObject class. The value attribute is used to specify the name of the property in the generated JSON, and the required attribute is used to indicate that the name property is required. The access attribute is used to indicate that the age property should be serialized as read-only.

When this code is run, it will output the following JSON string:

{"name":"John"}

The age property will not be included in the output as it is defined as READ_ONLY.

ObjectMapper is used to configure the serialization feature of the object, in this case, it is set to false to avoid error when serializing empty beans.