close
close
Converting JSON to Lowercase with Underscores Using Gson

Converting JSON to Lowercase with Underscores Using Gson

2 min read 09-11-2024
Converting JSON to Lowercase with Underscores Using Gson

When working with JSON data in Java applications, it's common to require specific formatting. One such format is transforming keys to be in lowercase with underscores. This can be particularly useful for maintaining consistency with naming conventions in databases or APIs.

What is Gson?

Gson is a popular library for converting Java Objects into their JSON representation and vice versa. It's developed by Google and provides a simple way to work with JSON in Java.

Steps to Convert JSON Keys to Lowercase with Underscores

To convert JSON keys to lowercase and replace camelCase with underscores, you'll need to create a custom FieldNamingStrategy. Below are the steps to achieve this using Gson.

Step 1: Add Gson Dependency

If you're using Maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

For Gradle, you can add it to your build.gradle:

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

Step 2: Create a Custom FieldNamingStrategy

You will need to implement a custom FieldNamingStrategy to convert the field names:

import com.google.gson.FieldNamingStrategy;

import java.lang.reflect.Field;

public class LowercaseUnderscoreNamingPolicy implements FieldNamingStrategy {
    @Override
    public String translateName(Field f) {
        // Convert the field name to lowercase and replace camelCase with underscores
        StringBuilder result = new StringBuilder();
        String name = f.getName();
        
        for (char c : name.toCharArray()) {
            if (Character.isUpperCase(c)) {
                if (result.length() != 0) {
                    result.append('_');
                }
                result.append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        
        return result.toString();
    }
}

Step 3: Use the Custom Naming Strategy in Gson

Now, configure Gson to use the custom naming strategy:

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

public class Main {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
                .setFieldNamingStrategy(new LowercaseUnderscoreNamingPolicy())
                .create();

        // Example object to convert
        MyClass myObject = new MyClass();
        myObject.setSomeValue("Hello");
        myObject.setAnotherValue("World");

        // Convert the object to JSON
        String json = gson.toJson(myObject);
        System.out.println(json);
    }
}

class MyClass {
    private String someValue;
    private String anotherValue;

    // Getters and Setters
    public String getSomeValue() {
        return someValue;
    }

    public void setSomeValue(String someValue) {
        this.someValue = someValue;
    }

    public String getAnotherValue() {
        return anotherValue;
    }

    public void setAnotherValue(String anotherValue) {
        this.anotherValue = anotherValue;
    }
}

Example Output

Running the above code will yield the following JSON output:

{
  "some_value": "Hello",
  "another_value": "World"
}

Conclusion

Using Gson with a custom FieldNamingStrategy, you can easily convert JSON keys to lowercase with underscores. This method provides flexibility and keeps your code clean while adhering to desired naming conventions. Whether working with REST APIs or storing data in a database, this technique can be crucial for consistency in your Java applications.

Popular Posts