Reputation: 2146
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:
Since I know how to do that (using transient for e and f) here is the catch:
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?
Upvotes: 1
Views: 945
Reputation: 76898
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.
Upvotes: 1