问题
I have an generic array of objects:
static Array<Level> allLevels = new Array<Level>();
Now I want to encode it to json like this:
Json json = new Json();
String levelsJsonString = json.prettyPrint(allLevels);
The problem occurs when I'm trying to reverse this process:
allLevels = json.fromJson(Level.class, levelsJsonString);
It is raising that Array and Level are incompatible types. How to do this?
回答1:
As far as I know there's always problem with passing generic type class to a json fromJson() method.
The simpliest workarround is just to wrap Array type like:
public class Levels
{
public static Array<Level> allLevels = new Array<Level>();
}
Then you can use it just like
Levels.allLevels.add( new Level() ); //etc...
and retrieve it from JSON like
... = json.fromJson(Levels.class, jsonLevels);
passing the wrapping class class object to fromJson method. The same you are doing hen converting to JSON - pass wrapping class not just Array object
String levelsJsonString = json.prettyPrint(Levels.allLevels);
来源:https://stackoverflow.com/questions/32813458/json-parse-and-encoding-with-generic-types