Java: Gson custom serializer and deserializer special requirement

南楼画角 提交于 2019-12-24 13:32:08

问题


I know how to implement JsonDeserializer and JsonSerializer, but here is what I want to do:

This is the setup:

public class classA
{
public String a;
public classB clazzB;
}

public class classB
{
public String c;
public String d;
public String e;
public String f;
}

I want to serialize (and deserialize analog to this) classA like this:

  • when serializing classA it should serialize a part of classB with it aswell, say variables c and d

Since I know how to do that (using transient for e and f) here is the catch:

  • c and d (the parts of classB that should be serialized with classA) should NOT be in a JSONObject, they should rather appear INLINE with the variable from classA

In essence the result should look something like this:

{"a":"something","c":"something", "d":"something"}

The problem I am having with JsonSerializer here is that there are 2 variables (could be more) I have to serialize from classB. If it were only one then I could just return a JSONPrimitive of the variable. I was thinking about using JsonTreeWriter in the serialize method but I doubt that can be done.

What is the most elegant way to do this?


回答1:


Other than "You're doing it wrong" since you're basically saying you don't want to serialize your Objects into the actual JSON equivalent... you don't serialize classB, because that's not what you want. You want a single JSON object with fields from two of your Objects.

You can just write a custom Deserializer and Serializer for A and create the JSON you're trying to create.

class ClassA
{
    public String a = "This is a";
    public ClassB clazzB = new ClassB();
}

class ClassB
{
    public String c = "This is c";
    public String d = "This is d";
    public String e;
    public String f;
}


class ASerializer implements JsonSerializer<ClassA>
{

    public JsonElement serialize(ClassA t, Type type, JsonSerializationContext jsc)
    {
        JsonObject jo = new JsonObject();
        jo.addProperty("a", t.a);
        jo.addProperty("c", t.clazzB.c);
        jo.addProperty("d", t.clazzB.d);
        return jo;
    }

}

public class Test 
{
    pubic static void main(String[] args) 
    { 
        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapter(ClassA.class, new ASerializer());
        String json = gson.create().toJson(new ClassA());
        System.out.println(json);
    }
}

Output:

{"a":"This is a","c":"This is c","d":"This is d"}

You could also go the route of serializing ClassB in that serializer, adding the elements in ClassA and returning that.



来源:https://stackoverflow.com/questions/13970871/java-gson-custom-serializer-and-deserializer-special-requirement

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