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", ...... }
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()
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With