GSON泛型序列化

GSON泛型序列化

问题描述:

可能重复:
使用gson反序列化泛型

Possible Duplicate:
deserializing generics with gson

所以我需要做:

Type fluentType = new TypeToken<BruteForceFluentImpl<GtlDigestor.Data>>() {}.getType();

代替

Type fluentType = new TypeToken<Fluent<T>>() {}.getType(); // <-- i want to be able to do something like this.

String json = gson.toJson(fluent, fluentType);

这意味着每次我必须为Fluent类指定不同的类型参数时,都需要更改代码以进行指定.现在,类型参数是GtlDigestor.Data.

This means that every time I have to specify a different type parameter for the Fluent class, I need to change my code in order to specify it. Right now, the type parameter is GtlDigestor.Data.

我该怎么做? (第二行代码无效)

How do I do this? (the second line of code won't work)

您需要在运行时告诉Gson实际的参数化类型(例如,BruteForceFluentImpl<GtlDigestor.Data>,包括实际的运行时原始类型和实际的类型参数值),因为Gson需要保存此信息.

You need to tell Gson the actual parameterized type (e.g. BruteForceFluentImpl<GtlDigestor.Data>, including the actual runtime raw type and the actual type parameter value) at runtime, because Gson needs to save this information.

使用TypeToken是获取Type的最简单方法,但是要使用它,您必须在源代码中对确切的类型进行硬编码(没有像T这样的类型参数).如果您想将代码放入将用于不同类型的方法中,则此方法可能应接受Type作为参数,调用者需要传递该参数.编码在调用方的位置,每个位置大概只能使用固定类型.

Using TypeToken is the easiest way to get a Type, but to use it you must hard-code the exact type in the source (no type parameters like T). If you would like to put the code in a method that will be re-used with different types, then perhaps this method should accept the Type as a parameter, which the caller needs to pass in. The type can then be hard-coded at the caller's location, each of which presumably only uses a fixed type.

或者,如果您需要基于原始类型和类型参数在运行时完全动态地生成Type,请参阅我对问题

Or, if you need to generate the Type completely dynamically at runtime based on the raw type and type parameters, see my answer for the question here.