Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize POJO to JSON with different names using GSON?

Tags:

java

json

gson

I have a POJO like this which I am serializing to JSON using GSON:

public class ClientStats {

    private String clientId;
    private String clientName;
    private String clientDescription;

    // some more fields here


    // getters and setters

}

Here is how I am doing it:

ClientStats myPojo = new ClientStats();

Gson gson = new Gson();
gson.toJson(myPojo);

Now my json will be like this:

{"clientId":"100", ...... }

Now my question is: Is there any way I can come up with my own name for clientId instead of changing the clientId variable name? Is there any annotation in Gson that I can use here on top of clientId variable?

I want something like this:

{"client_id":"100", ...... }
like image 465
user1950349 Avatar asked Sep 13 '15 08:09

user1950349


2 Answers

You can use @SerializedName("client_id")

public class ClientStats {

    @SerializedName("client_id")
    private String clientId;
    private String clientName;
    private String clientDescription;

    // some more fields here


    // getters and setters

}

Edit:

You can also use this, which change all fields in a generic way

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create()
like image 75
Derek Fung Avatar answered Oct 17 '22 04:10

Derek Fung


A step further is to write your serializer that implements GSON serializer JsonSerializer :

import com.google.gson.JsonSerializer;

public class ClientStatsSerialiser implements JsonSerializer<ClientStats> {

@Override
public JsonElement serialize(final ClientStats stats, final Type typeOfSrc, final JsonSerializationContext context) { 
       final JsonObject jsonObject = new JsonObject();
       jsonObject.addProperty("client_id", stats.getClientId());
       // ... just the same thing for others attributes.
       return jsonObject;
    }
}

Here you don't need any annotations and you can write more than one custom serializer.

Example of main class to use it:

package foo.bar;

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

public class Main {

  public static void main(final String[] args) {
  // Configure GSON
  final GsonBuilder gsonBuilder = new GsonBuilder();
  gsonBuilder.registerTypeAdapter(ClientStats.class, new ClientStatsSerialiser());
  gsonBuilder.setPrettyPrinting();
  final Gson gson = gsonBuilder.create();

  final ClientStats stats = new ClienStats();
  stats.setClientId("ABCD-1234"); 

  // Format to JSON
  final String json = gson.toJson(stats);
  System.out.println(json);
  }
}
like image 22
André Blaszczyk Avatar answered Oct 17 '22 02:10

André Blaszczyk