从json字符串解析时未调用的对象构造函数

时间:2014-05-21 21:41:54

标签: java json gson

为什么没有调用IACircle构造函数? 这就是我加载Json的方式..

BufferedReader br = new BufferedReader(in);
LevelDefinition ld = new Gson().fromJson(br, LevelDefinition.class);

Json string ..

{
    "iaCircles": [
        {
            "x": -32.0,
            "y": -5.0,
            "angle": 0.0,
            "radius": 2.5,
            "density": 0.0,
            "friction": 0.0,
            "restitution": 1.0,
            "textureSelection": "CIRCLE",
            "inflictsDamage": true,
            "fixedRotation":true
        },
        {
            "x": 55.0,
            "y": -5.0,
            "angle": 0.0,
            "radius": 2.5,
            "density": 0.0,
            "friction": 0.0,
            "restitution": 1.0,
            "textureSelection": "CIRCLE",
            "inflictsDamage": true,
            "fixedRotation":true
        }
    ]
}

Java类解析为..

public class LevelDefinition {

    private Vector<IACircle> iaCircles;
}

IACircle定义..

public class IACircle {
    public IACircle (
        float x, float y, float angle, float radius,
        float density, float friction, float restitution,
        String textureSelection, boolean inflictsDamage, boolean fixedRotation) { 
        System.out.println("constructor called, circle");
    }
}

1 个答案:

答案 0 :(得分:2)

您应该为您的类定义默认的no-args构造函数。 GSON只调用no-args构造函数来初始化一个类。你有一个带参数的构造函数,这就是它没有被调用的原因;它会创建一个ObjectConstructor来启动。试试这个:

public class IACircle {
    public IACircle () { 
        System.out.println("constructor called, circle");
    }
}