Gson Tip: Using a different FieldNamingPolicy


Today, while write a client for a REST API I had the need to use a different field naming strategy than the default one. By default, when Gson tries to convert a JSON String to an object it expects field names in JSON to be same as field name in the converting object. For example, you can convert following JSON String to Message object as shown below.

{
"message": "hello world!"
}
public class Message{
private String message;
// setters and getters
}

To convert to message JSON to Message object you can use following code.

// String json
Message message = new Gson().fromJson(json, Message.class);

This will not work if JSON has different naming policy(first letter upper case) as shown below.

{
"Message": "hello world!"
}

To make it work, you can use GsonBuilder to create Gson with UPPER_CAMEL_CASE as field naming policy. This is shown below.

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
Message message = gson.fromJson(json, Message.class);

Discover more from Shekhar Gulati

Subscribe to get the latest posts sent to your email.

One thought on “Gson Tip: Using a different FieldNamingPolicy”

  1. I really appreciate this detailed explanation! It’s so true that handling different naming conventions can be a bit tricky. I remember running into a similar issue where my API response had inconsistent naming, and it was a lifesaver to learn about customizing Gson’s field naming policy. It’s these little adjustments that make working with APIs much smoother. In the broader context of data engineering services, ensuring smooth data transformations and integrations often involves these kinds of nuanced solutions. Thanks for breaking this down so clearly!

Leave a reply to Divyanshu Cancel reply