I'm using GSON for deserializing some JSON data and I'm interested in a way to pass some contextual values into the deserialization process. To be more specific, suppose we have 2 classes:
class A {
String relativePath;
transient B contextDependentValue;
}
class B {
int y;
A z;
}
and a JSON as follows:
{
y: 2,
z: {
relativePath: "./foo/bar"
}
}
When trying to deserialize things, I'd like to populate the contextDependentValue
field in the nested object with something that is dependent on where the context of deserialization (e.g. contextDependentValue
could be the absolute path on which the JSON was found, so I could then build the full path as contextDependentValue + '/' + relativePath
). These context values would be set for each deserialization.
Ideally, I would be able to build a custom JsonDeserializer
that gets a context values holder when asked to deserialize:
public T deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context,
Map<String, Object> someSortOfContextValuesHolder) {
return buildObjectWithContext(json, someSortOfContextValuesHolder);
}
and where someSortOfContextValuesHolder
would be provided when starting each deserialization:
gson.fromJson(json, B.class, someSortOfContextValuesHolder)
Any ideas on how I could implement something like this?