Reputation: 9454
Let's say I have a some basic types:
public class Base {
String a = "a";
Nested nested = new Nested()
}
public class Nested {
String b = "b",
}
Serialising this with GSON, I get:
{
"a": "a",
"nested": {
"b": "b"
}
}
This is all good, but what if I want to preserve the object type as well, according to the following:
{
"Base":
{
"a": "a",
"nested": {
"Nested": {
"b": "b"
}
}
}
}
I could try writing a custom serializer to solve this (Just assume an equivalent one is written for Nested as well):
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 that I get stuck in an infinite recursion when serializing the base type.
Is there any other way to solve this?
Upvotes: 3
Views: 750
Reputation: 35557
You can try in 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());
Out put:
{"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\":",""));
Out put:
{"Base","a":"a","nested":{"Nested","b":"b"}}
Upvotes: 1
Reputation: 2810
Why not just add the class name in top of object tree. You could have something like this.
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(new Base());
JsonObject jo = new JsonObject();
jo.add(Base.class.getSimpleName(), je);
Upvotes: 0
Reputation: 9813
Just subclass the gson serializer and serialize the object as normal. Once you have it, get the class name using introspection and set it as the key to a new map with the value being gson's json object. Return this object now from your custom serialize method.
Don't override the custom serialize method, jus create a new one that uses the original serialize method.
Upvotes: 0