Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson add field during serialization

I can't find a simple way to add a custom field during serialization in Gson and I was hoping someone else may be able to help.

Here is a sample class to show my issue:

public class A {   String id;   String name;   ... } 

When I serialize class A I would like to return something like:

{ "id":"123", "name":"John Doe", "url_to_user":"http://www.example.com/123" } 

where url_to_user is not stored in my instance of class A, but can be generated with data in the instance of class A.

Is there a simple way of doing this? I would prefer to avoid writing an entire serializer just to add one field.

like image 929
joncalhoun Avatar asked Oct 23 '12 06:10

joncalhoun


People also ask

Does Gson serialize private fields?

In this example you'll see how the Gson library handles the object fields. For object fields to be serialized into JSON string it doesn't need to use any annotations, it can even read private fields.

Does Gson ignore extra fields?

3. Deserialize JSON With Extra Unknown Fields to Object. As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

How do I exclude a field from serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do I ignore fields in Gson?

ExclusionStrategy strategy = new ExclusionStrategy() { @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } @Override public boolean shouldSkipField(FieldAttributes field) { return field. getAnnotation(Exclude. class) !=


1 Answers

Use Gson.toJsonTree to get a JsonElement, with which you can interact dynamically.

A a = getYourAInstanceHere(); Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(a); jsonElement.getAsJsonObject().addProperty("url_to_user", url); return gson.toJson(jsonElement); 
like image 74
Jeff Bowman Avatar answered Sep 21 '22 18:09

Jeff Bowman