Java PropertyNamingStrategy-class And Method Code Example


The PropertyNamingStrategy class from the com.fasterxml.jackson.databind package is used to define a strategy for naming properties when serializing and deserializing Java objects to and from JSON. This class can be used to customize the naming conventions used for properties, for example, to convert between camelCase and snake_case.

Here is an example of how to use the PropertyNamingStrategy class with the ObjectMapper class to customize the naming conventions used for properties:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

public class MyClass {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        MyObject obj = new MyObject();
        obj.setFirstName("John");
        obj.setLastName("Doe");

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

class MyObject {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

In this example, the ObjectMapper class is configured to use the SNAKE_CASE naming strategy, which converts property names from camelCase to snake_case. The MyObject class has two properties, firstName and lastName, which are serialized to JSON using the snake_case naming convention.

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

{"first_name":"John","last_name":"Doe"}

The ObjectMapper class provides several predefined naming strategies, such as SNAKE_CASE, LOWER_CAMEL_CASE, UPPER_CAMEL_CASE and LOWER_CASE that can be used to customize the naming conventions used for properties.

Additionally, you can also create a custom naming strategy by creating a class that implements the PropertyNamingStrategy interface and overrides the translate method to define the custom naming logic.