为什么我的 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 ..
}
字符
实现..
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 的构造函数不会被调用。
如果您需要在此处执行一些奇特的逻辑,您可以使用 Json.Serialized
编写自己的反序列化逻辑,如 Customizing Serialization 中所述。 .
关于java - 使用libgdx反序列化json时调用对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507466/