Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson - Serialize Nested Object as Attributes

Is there an easy way to convert how a nested Object is converted to JSON? I'm trying to just create one JSON object to match the back-end. I'm using Retrofit for my networking, which converts an Object to JSON with Gson.

I don't have access to any code between network call and the convertion, so I'm trying to find a clean way to modify how the Object is converted, either through the GsonBuilder, or Annotations.

// Automatically converted to JSON with passed in Gson.
Call<myObject> search( @Body foo myFoo ); 

public class foo {
    String text = "boo";
    bar b = new bar();
}

public class bar {
    String other = "moo";
}

Result:

{ "text": "boo", "b" { "other": "moo" } }

Desired Result:

{ "text": "boo", "other": "moo" }

Thanks for your help. :)

like image 637
Advice-Dog Avatar asked Feb 11 '16 21:02

Advice-Dog


1 Answers

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.

like image 188
pratikpawar Avatar answered Sep 19 '22 12:09

pratikpawar