Include Object Type When Serializing With GSON
Let's say I have several basic types:
public class Base {
String a = "a";
Nested nested = new Nested()
}
public class Nested {
String b = "b",
}
Serializing this with GSON I get:
{
"a": "a",
"nested": {
"b": "b"
}
}
That's all well and good, but what if I want to keep the type of the object, according to the following:
{
"Base":
{
"a": "a",
"nested": {
"Nested": {
"b": "b"
}
}
}
}
I could try writing my own serializer to solve this problem (just assume the equivalent is written for Nested):
new JsonSerializer<Base>() {
@Override
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
Map<String, Base> selfMap = new HashMap<>();
selfMap.put(src.getClass().getSimpleName(), src);
return context.serialize(selfMap);
}
}
The problem with this, however, is of course I am stuck with infinite recursion when serializing the base type.
Is there any other way to solve this problem?
source to share
You can try this way
Base base = new Base();
base.a="a";
base.b="b";
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(base);
JsonObject jo = new JsonObject();
jo.add(Base.class.getName(), je);
System.out.println(jo.toString());
Output:
{"Base":{"a":"a","b":"b"}}
Edit:
for your edit in the question.
You can try with Genson
Base base = new Base();
base.a="a";
base.nested=new Nested();
Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
String json = genson.serialize(base);
System.out.println(json.replaceAll("\"@class\":",""));
Output:
{"Base","a":"a","nested":{"Nested","b":"b"}}
source to share
Just subclass the gson serializer and serialize the object as usual. Once you get it, get the class name using introspection and set it as a key to the new map with the value being a gson json object. Return this object from your custom serialization method.
Don't override your own serialization method, jus create a new one that uses the original serialization method.
source to share