【问题标题】:Invoke object constructor when deserializing json using libgdx使用 libgdx 反序列化 json 时调用对象构造函数
【发布时间】:2015-07-20 00:41:55
【问题描述】:

我的player 的对象构造函数为什么在反序列化期间没有被调用?有没有办法使用这种方法调用构造函数?

使用com.badlogic.gdx.utils.Json ..将json加载到java对象中。

LevelModel ld = new Json().
    fromJson(LevelModel.class, Gdx.files.internal("levels/level1.json"));
setLevel(new Level(ld));

这是我的JSON ..

{
    "gravity": {
        "x": 0.0,
        "y": 0.0
    },

    "sounds": [
        BGMUSIC
    ],

    "player": {
        "maxSpeed": 10.0
    }
}

LevelModel.java 看起来像这样..

public class LevelModel {

    private Vector2 gravity;
    private Vector<AudioCollection> sounds = new Vector<AudioCollection>();
    private Character player;

    // with getters/setters for each ..
}

Character 实现..

public class Character {

    private float maxSpeed;

    public Character (){
        System.out.println("empty - charercter constr");
    }

    /**
     * @param speed
     */
    public Character(float maxSpeed) {

        System.out.println("charercter constr");
        setMaxSpeed(maxSpeed);
    }

    // with getters/setters for each ..
}

【问题讨论】:

    标签: java json libgdx


    【解决方案1】:

    默认情况下,libgdx json 使用反射来生成反序列化实例。因此它将创建一个空对象,然后将字段值添加到其中。不会调用设置玩家 maxSpeed 的构造函数。

    如果您需要在此处执行一些奇特的逻辑,您可以使用Json.Serializable 编写自己的反序列化逻辑,如Customizing Serialization 中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多