使用libgdx反序列化json时调用对象构造函数 [英] Invoke object constructor when deserializing json using libgdx

查看:123
本文介绍了使用libgdx反序列化json时调用对象构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How come my objects constructor for player is not called during deserialization? Is there a way to invoke the constructor using this approach?

使用com.badlogic.gdx.utils.Json ..

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

推荐答案

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

By default libgdx json uses reflection to generate instances on deserialization. So it will create an empty object and then add the field values to it. Your constructor that sets the player's maxSpeed won't be called.

如果您需要在此处执行一些特殊的逻辑,则可以使用Json.Serializable编写自己的反序列化逻辑,如

If you need some fancy logic to be executed here you can write your own deserialization logic using Json.Serializable as described under Customizing Serialization.

这篇关于使用libgdx反序列化json时调用对象构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆