Convert Camel Case To Underscore In JSON With Gson

9 min read 11-15- 2024
Convert Camel Case To Underscore In JSON With Gson

Table of Contents :

When dealing with JSON data in Java, developers often encounter varying naming conventions, one of the most common being camel case. However, when interfacing with systems or frameworks that prefer the underscore format (often used in databases or in certain programming languages), you may need to convert JSON keys from camel case to underscore format. This article will explore how to achieve this using the popular Gson library in Java. Let's delve deeper into the conversion process and why it is important! ๐ŸŒŸ

Understanding the Terminology

Before we dive into the conversion, let's clarify what camel case and underscore formats are:

  • Camel Case: In this style, words are joined without spaces, and each word starts with an uppercase letter except for the first one, e.g., firstName, lastName, dateOfBirth.

  • Underscore Format: In this style, words are separated by underscores, with all letters typically in lowercase, e.g., first_name, last_name, date_of_birth.

Why Convert Camel Case to Underscore? ๐Ÿค”

  1. Interoperability: Some databases and APIs use underscore naming conventions, making it necessary to adapt your JSON keys to ensure seamless communication between systems.

  2. Readability: Underscore format can improve the readability of keys in certain contexts.

  3. Consistency: If your project uses a mix of naming conventions, converting keys to a uniform format can help maintain consistency across the codebase.

Setting Up Gson for JSON Conversion

To start with, you'll need the Gson library, which is a powerful tool for converting Java objects to JSON and vice versa. You can include Gson in your project by adding the following dependency to your pom.xml if you're using Maven:


    com.google.code.gson
    gson
    2.8.9

If you're using Gradle, include this in your build.gradle file:

implementation 'com.google.code.gson:gson:2.8.9'

The Conversion Process

Step 1: Define a Custom Naming Policy

Gson allows us to define a custom naming policy to convert camel case keys into underscore format. To do this, we'll create a class that implements FieldNamingStrategy.

import com.google.gson.FieldNamingStrategy;
import java.lang.reflect.Field;

public class CamelCaseToUnderscoreNamingStrategy implements FieldNamingStrategy {
    @Override
    public String translateName(Field field) {
        StringBuilder name = new StringBuilder();
        String fieldName = field.getName();
        
        for (int i = 0; i < fieldName.length(); i++) {
            char c = fieldName.charAt(i);
            // If the character is upper case, prepend an underscore
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    name.append('_');
                }
                name.append(Character.toLowerCase(c));
            } else {
                name.append(c);
            }
        }
        
        return name.toString();
    }
}

Step 2: Configure Gson with the Custom Naming Strategy

Now, we need to configure our Gson instance to use the custom naming strategy we just created.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonConfiguration {
    public static Gson createGson() {
        return new GsonBuilder()
                .setFieldNamingStrategy(new CamelCaseToUnderscoreNamingStrategy())
                .create();
    }
}

Step 3: Convert a Java Object to JSON

With the configuration set up, you can now convert Java objects into JSON while automatically transforming the field names.

public class User {
    private String firstName;
    private String lastName;
    private String dateOfBirth;

    // Constructors, Getters, and Setters
    public User(String firstName, String lastName, String dateOfBirth) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.dateOfBirth = dateOfBirth;
    }

    // Getters
    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }
}

Example Usage

Now, let's put everything together to see the conversion in action.

public class Main {
    public static void main(String[] args) {
        User user = new User("John", "Doe", "1990-01-01");
        Gson gson = GsonConfiguration.createGson();
        
        String json = gson.toJson(user);
        System.out.println(json);
    }
}

Expected Output

Running the above code should yield the following JSON output:

{"first_name":"John","last_name":"Doe","date_of_birth":"1990-01-01"}

As you can see, the camel case keys have been successfully converted to underscore format! ๐ŸŽ‰

Important Notes

Remember: This conversion process only affects the serialization of Java objects to JSON. Deserialization (i.e., converting JSON back to Java objects) will also require a similar approach if the JSON uses underscore keys.

Handling Nested Objects

If your JSON structure contains nested objects, the same naming strategy will automatically apply to those nested fields, ensuring a consistent format throughout your JSON data.

Example with Nested Objects

public class Address {
    private String streetAddress;
    private String city;

    public Address(String streetAddress, String city) {
        this.streetAddress = streetAddress;
        this.city = city;
    }

    // Getters
    public String getStreetAddress() {
        return streetAddress;
    }

    public String getCity() {
        return city;
    }
}

public class UserWithAddress {
    private String firstName;
    private String lastName;
    private Address address;

    public UserWithAddress(String firstName, String lastName, Address address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }

    // Getters
    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public Address getAddress() {
        return address;
    }
}

Serialization Example

public class Main {
    public static void main(String[] args) {
        Address address = new Address("123 Main St", "Springfield");
        UserWithAddress user = new UserWithAddress("John", "Doe", address);
        Gson gson = GsonConfiguration.createGson();
        
        String json = gson.toJson(user);
        System.out.println(json);
    }
}

Expected Output for Nested Objects

The output will look something like this:

{"first_name":"John","last_name":"Doe","address":{"street_address":"123 Main St","city":"Springfield"}}

This illustrates how Gson's naming strategy applies uniformly to nested objects as well! ๐Ÿš€

Conclusion

Converting JSON keys from camel case to underscore format using Gson is a straightforward process that enhances the interoperability of your Java applications. By defining a custom FieldNamingStrategy, you can seamlessly transform Java objects to JSON without extensive boilerplate code. With these steps, your Java applications will effectively handle varying naming conventions, providing better integration with external systems and improving overall consistency.

Don't forget to also consider reverse conversion for deserialization, as maintaining consistency throughout your application is key to successful data management. Happy coding! ๐Ÿ’ปโœจ