Gson - Serialize Nested Object as Attributes

亡梦爱人 提交于 2020-01-12 17:30:31

问题


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. :)


回答1:


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.




回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/35350183/gson-serialize-nested-object-as-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!