简体   繁体   中英

How to deserialize object of specific type from JSON in Java if it was serialized to JSON as Object?

I'm new in Java!

My goal: I have collection of Objects which lets me to keep objects of any types by some key (like Map) (put them to it and get from). I can add objects of any type to it (for example I can add object of MyClass). Then I serialize this object to separate string in JSON format using GSON (then I can serialize this string to separate file, for example). When I want to get some object back I request it from collection by key and collection deserializes corresponding string to Object object and return me it. Then I cast it to MyClass to be able to use this object.

The code below skips work with the collection:

    Gson gson = new Gson();
    Object myClass = new MyClass(); //imitation of putting MyClass object to Collection
    String json = gson.toJson(myClass); //serializing to JSON
    Object myClass1 = gson.fromJson(json, Object.class); //imitation of deserializing and getting object from collection
    Main.MyClass myClass2 = (Main.MyClass) myClass1;

The last string of this code throws java.lang.ClassCastException, because "gson.fromJson(json, Object.class);" returns object of type "com.google.gson.internal.LinkedTreeMap"

How I can reach my goal???

This might be because when you use gson.fromJson(json, Object.class) , you cast it to an object and not to your MyClass, maybe if you use gson.fromJson(json, MyClass.class) and then cast it that it will return the correct values. Otherwise they will make a simple object class.

gson.fromJson(json, Object.class); cast to LinkedTreeMap (see gson sources at ObjectTypeAdapter.read(JsonReader in) ).

Try this:

Gson gson = new Gson();
Object myClass = new MyClass(); //imitation of putting MyClass object to Collection
String json = gson.toJson(myClass); //serializing to JSON
Main.MyClass myClass2 = gson.fromJson(json, Main.MyClass.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM