Shared context during object deserialization

时间:2015-10-06 08:57:34

标签: java json gson

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?

1 个答案:

答案 0 :(得分:0)

查看Gson's TypeAdaptor

  

默认情况下,Gson使用其内置类型适配器将应用程序类转换为JSON。如果Gson的默认JSON转换不适合某种类型,请扩展此类以自定义转换。

这篇关于how-to-handle-deserializing-with-polymorphism的stackoverflow文章也展示了可能证明相关的示例代码示例,并帮助您解决了一些问题。

如果您对运行时的编组感兴趣,请查看RuntimeTypeAdapterFactory

  

调整运行时类型可能与其声明类型不同的值。

...这些关于convert-from-json-to-multiple-unknown-java-object-types-using-gsonhow-to-deserialize-a-list-of-polymorphic-objects-with-gson的文章也可能有用。