Kafka Streaming Json using Gson: How to rename a json field? (Actually this is a Gson topic)


If you are reading in from a topic to which you sent data formatted as Json you must serialize the data, optionally process it and finally you serialize it again. Here, I assume you are using Gson for the processing the json. If you want to rename a fieldname you need to do this when serializing it. So in your serializer you create a Gson instance using GsonBuilder:

private Gson gson = new GsonBuilder().setFieldNamingStrategy(new DurationStrategy()).create();

In the above example I call a method which I called DurationStrategy(). GsonBuilder lets you configure the Gson object which it creates.

DurationStrategy is the implementation of theĀ  FieldNamingStrategy interface:

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

class DurationStrategy implements FieldNamingStrategy {
     public String translateName(Field field) {
         if (field.getName().equals("timestamp_start")) {
             return "blablabla";
         return field.getName();

Assuming the incoming json contains a field that you cannot process in Java, e.g. [‘a_field’=some_val’, ‘class’=another_val’…]

In this case Gson offers a handy notation called @SserializedName, which can be used as shown in the following example:

@SerializedName("class") private String cla

In the rest of your code you can use the variable “cla”.

Was this helpful?

1 / 0