2

I'm using GSON for deserializing JSON-Strings in my Android-App. My problem is, that I don't retrieve the expected objects, but LinkedTreeMap-objects, what causes an exception:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to sis.hierrein.android.DDL.Core.Uniqueidentifier

My classes:

public class Uniqueidentifier {
    public String OID;
}

public class Element extends Uniqueidentifier {
    (...)
}

The methods, that implement the deserialization:

public void Set(String data) throws Exception {
    HashSet<T> objList = loadObject(data);

    if(objList == null) {
        throw new Exception("Es wurden keine Daten übergeben.");
    }

    for(T obj: objList) {
        // Trying to iterate over each element causes the exception
    }
}

// T is in this example Element
protected HashSet<T> loadObject(String data)  {
    Gson parser = new Gson();
    HashSet<T> obj;

    Type t = new TypeToken<HashSet<T>>(){}.getType();

    try {
        obj = parser.fromJson(data, t);
    }
    catch(Exception e) {
        return null;
    }

    return obj;
}

The class

public class Handler<T extends Uniqueidentifier> {  
    (...)
}

which contains this methods, is used as the superclass of

public class ElementHandler extends Handler<Element> {
    (...)
}

ElementHandler itself only contains a constructor, so the methods of the superclass are called. Background: all these classes are instantiated / methods are called via reflection.

Sven Kannenberg
  • 859
  • 2
  • 10
  • 20
  • Similar question had this answer http://stackoverflow.com/a/17694308/1321873 – Rajesh Jul 26 '13 at 10:02
  • 2
    Gson don't know what to do with `T`. You need to provide the generic. https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Generic-Types – PomPom Jul 26 '13 at 13:00

0 Answers0