mardi 29 mars 2016

Java: Dynamic List Type to cast Json array

Well, I have this: A number of webservices, each webservice returns an array of one entity. Good!

In my Android app, I call the webservices and get the Json String with the array of elements.

To make it some dynamically I made an array with the cast classes names, example:

<item>com.company.package.Person</item>
<item>com.company.package.Animal</item>
<item>com.company.package.Thing</item>
// etc

The idea was:

  1. Load the array with the name of the class to cast the JSON

    String[] entities = getResources().getStringArray(R.array.classNames);
    
    
  2. Get a Class type with Class.forName(...)

    Class<?> object = Class.forName(entities[y]); 
    
    
  3. Always the webservices returns an array, then I want to convert the Json to Java List like this

    //see the **object**, this was my idea but doesn't work
    Type type = new TypeToken<List<**object**>() {}.getType();
    List<**object**> array = gson.fromJson(jsonArrayString, type);
    
    

Any way to do this?





Aucun commentaire:

Enregistrer un commentaire