Search code examples
javaandroidgson

How to check Type in android


One of my function getting Type variable. sometimes it can be java.util.List<Test$MyClass> or java.util.List<java.lang.String> so how can I identify them?

if (type instanceof List) {

}

Both are List type but different type. So that above code does not work. I want to distinguish between the two list types.

my main issue is https://stackoverflow.com/questions/15596112/implement-jsondeserializer-more-than-one-in-gson-in-android

I am using deserializer for that..

public class Data implements JsonDeserializer<ArrayList<MyClass1>> {
public ArrayList<MyClass1> myList1 = new ArrayList<MyClass1>();
public ArrayList<MyClass2> myList2 = new ArrayList<MyClass2>();

@Override
public ArrayList<MyClass1> deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

    Debug.e("", type.toString());

    ArrayList<Layoutmap> data = new ArrayList<Layoutmap>();

    try {
        if (json.isJsonObject()) {

            // my stuff

            return data;
        } else {
            return new Gson().fromJson(json, type);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return data;
}

}

above code works for public ArrayList<MyClass2> myList2 = new ArrayList<MyClass2>(); and myList2 is also i want to deserialize.. It's part of google Gson.


Solution

  • I just find my solution .. I don't know it is better or not

    I am comparing two Type variable like this...

    if (type.toString().equalsIgnoreCase(
                    new TypeToken<List<Test.MyClass>>() {
                    }.getType().toString())) {
    
    }else
    {
    
    }