JSON解析和编码与泛型类型

JSON解析和编码与泛型类型

本文介绍了JSON解析和编码与泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的泛型数组:

    static Array<Level> allLevels = new Array<Level>();

现在我要带code将其以JSON是这样的:

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);

据提高了阵列和Level是不兼容的类型。如何做到这一点?

It is raising that Array and Level are incompatible types. How to do this?

推荐答案

据我知道总会有问题通过的泛型类以一个JSON fromJson()方法。

As far as I know there's always problem with passing generic type class to a json fromJson() method.

该simpliest workarround只是包装数组类型,如:

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...

和JSON从检索它像

    ... = json.fromJson(Levels.class, jsonLevels);

通过包装类的类对象以fromJson方法。你正在做的母鸡转换成JSON一样的 - 通包装类不只是数组对象

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);

这篇关于JSON解析和编码与泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:49