0

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?

Cosmin SD
  • 1,467
  • 3
  • 14
  • 21

1 Answers1

0

Have a look at Gson's TypeAdaptor

By default Gson converts application classes to JSON using its built-in type adapters. If Gson's default JSON conversion isn't appropriate for a type, extend this class to customize the conversion.

This stackoverflow article about how-to-handle-deserializing-with-polymorphism also shows sample code samples which may prove relevant and help you out a bit.

Should you be interested in marshalling at runtime you should look into RuntimeTypeAdapterFactory

Adapts values whose runtime type may differ from their declaration type.

...and these article about convert-from-json-to-multiple-unknown-java-object-types-using-gson and how-to-deserialize-a-list-of-polymorphic-objects-with-gson might also prove useful.

Community
  • 1
  • 1
Filip
  • 1,214
  • 10
  • 19
  • The problem with the TypeAdaptor and the JsonDeserializer are that they are set once and work for __all__ the deserialization. I am more interested in a way to customize that adaptor at each call, taking into account that it could work on multiple threads. – Cosmin SD Oct 06 '15 at 09:25
  • I've updated my original answer with details around Gson support for runtime type based marshalling, let me know if those are helpful... – Filip Oct 06 '15 at 09:34