Gson - Serialize Nested Object as Attributes Gson - Serialize Nested Object as Attributes json json

Gson - Serialize Nested Object as Attributes


Update I looked into GsonBuilder and yes you can do it with custom serialization. You need to override serialize method of JsonSerializer<type>

Just define a class as below. here only 2 properties are added.

public class FooSerialize implements JsonSerializer<foo> {@Override    public JsonElement serialize(foo obj, Type foo, JsonSerializationContext context) {         JsonObject object = new JsonObject();         String otherValue = obj.b.other;         object.addProperty("other", otherValue );         object.addProperty("text", obj.text);         return object;    }  }

Create gson object as below.

Gson gson = new GsonBuilder().registerTypeAdapter(foo.class, new FooSerialize()).setPrettyPrinting().create();

Just convert to Json

 gson.toJson(fooObject);

Voila! lmk if it works for you. I tested on my system it worked. Forget about to string override it gets called for Json to Obj conversion. This is only serialization you need to handle deserialize to object as well. Look for online resources to get an idea on similar line.

Alternate solution would be define dummy pojos only for JSON conversion purposes. While sending use setters to assign values to pojo object and use gson on pojo vice versa or above solution to have custom serialize and deserialize for class you need.


To add a bit more details to what I was trying to accomplish, let me show what I wrote, as it may help someone else who's trying to do the same thing. While my parent Object ( foo ) only has a few variables, my child Object ( bar ) has a long list of possible variables.

I did find out you can loop through the child's entries and manually add them to the parent. Unfortunately, this has the side effect of often adding unwanted values, like my constants, or any Integer with a value of '0'.

Hope this helps someone.

public class FooSerializer implements JsonSerializer<Foo> {     @Override     public JsonElement serialize(Foo src, Type typeOfSrc, JsonSerializationContext context) {         JsonObject object = new JsonObject();         object.addProperty("text", src.text);         bar myBar = src.getBar();         // Using the context to create a JsonElement from the child Object.         JsonElement serialize = context.serialize(myBar, bar.class);         JsonObject asJsonObject = serialize.getAsJsonObject();         // Getting a Set of all it's entries.         Set<Map.Entry<String, JsonElement>> entries = asJsonObject.entrySet();         // Adding all the entries to the parent Object.         for (Map.Entry<String, JsonElement> entry : entries) {             object.addProperty(entry.getKey(), entry.getValue().toString());         }              return object;    }}