问题
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