Reputation: 1
I am trying to serialize a class where one of the members comes with its own implementation of JSON Serialization. I'm not sure how to include it with the rest of the properties. For example
class Foo {
String fieldA;
String fieldB;
Bar bar;
}
class Bar
has a method toJSONString()
. Currently I am including it by registering a JsonSerializer
as TypeAdapter
something like :
class BarSerializer implements JsonSerializer<Bar> {
@Override
public JsonElement serialize(Bar bar, Type type, JsonSerializationContext ctxt) {
return new JsonParser().parse(bar.toJSONString());
}
}
I cannot change the code of Bar
or I cannot serialize it using its fields directly as it has some deeply nested structure and I don't have any control over its member class types. As you can see in the above method the Bar
object is serialized, parsed and serialized again.
Is there any other simple/efficient way of serializing Bar
within Foo
?
Upvotes: 0
Views: 757
Reputation: 15543
If you want an efficient way, it is suggested to use TypeAdapter
Below explanation is copied from JsonSerializer's document:
New applications should prefer TypeAdapter, whose streaming API is more efficient than this interface's tree API.
Check out this link for some good examples about TypeAdapter.
Upvotes: 1