JSON parse and encoding with generic types

淺唱寂寞╮ 提交于 2019-12-25 06:54:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!