1


public class Feature{
   private String name;
   private int score;
   Object value;
}

Now when serializing/deserializing :

Type mapType = new TypeToken<Map<String, Feature>>(){}.getType();
Map<String, Feature> map = gson.fromJson(string,mapType);

The Feature objects are being created correctly, but the inner value attribute does not retain its type. Instead of an object what gson returns is a TreeMap with keys the names of the objects fields and values their respective values. Is there any way to use GSON to deserialize java Object?

carlos palma
  • 722
  • 3
  • 12
  • 29
  • You must retain the original type name/token/whatever in the `value` property value and make sure you have a type adapter (+factory) to recognize the type name/token/whatever in order to deserialize the object properly. Having no that information, Gson is unable to know the original type of the value (e.g., `{}` -- is it an empty map, or a DTO class without serializable fields?). If you have a finite (and relatively short) set of types to be handled in the `value` property, then you can use an extra class from Gson: https://stackoverflow.com/a/22081826/12232870 . – terrorrussia-keeps-killing Apr 19 '21 at 20:32
  • 1
    If you want to handle a lot of types, then you can patch `RuntimeTypeAdapterFactory` so that it could emit type names and then parse it to restore the original value type. Having no that information, Gson deserializes `Object`s as maps. Note that you can't override the `Object` type adapter factory. – terrorrussia-keeps-killing Apr 19 '21 at 20:33
  • For the "infinite" set of types please see https://stackoverflow.com/questions/66969001 for some ideas on how variable types can be represented. – terrorrussia-keeps-killing Apr 19 '21 at 20:39
  • Hello fluffy, can you make your second comment an aswer so I can accept it? @fluffy – carlos palma May 19 '21 at 13:29
  • It would require more work, otherwise it is more or less a duplicate of questions for `RuntimeTypeAdapterFactory` on S.O., so you can share your solution as answer as well. By the way, I was wrong regarding Gson not being able to override `Object`. It can if the field is annotated with `@JsonAdapter` (a `TypeAdapterFactory` implementation with logs can prove that.) – terrorrussia-keeps-killing May 19 '21 at 14:21

0 Answers0