Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON generics serialization [duplicate]

Possible Duplicate:
deserializing generics with gson

So I need to do:

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

instead of

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

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

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)

like image 444
Michael Studebaker Avatar asked Oct 23 '25 02:10

Michael Studebaker


1 Answers

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.

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.

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.

like image 50
newacct Avatar answered Oct 24 '25 14:10

newacct



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!