Invoke object constructor when deserializing json using libgdx

廉价感情. 提交于 2019-12-11 03:29:09

问题


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

Load json into java object using com.badlogic.gdx.utils.Json ..

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

Heres my JSON ..

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

    "sounds": [
        BGMUSIC
    ],

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

LevelModel.java looks like this ..

public class LevelModel {

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

    // with getters/setters for each ..
}

Character implementation ..

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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/31507466/invoke-object-constructor-when-deserializing-json-using-libgdx

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