gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:48:31 24 4
gpt4 key购买 nike

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

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

Json 字符串..

{
"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");
}
}

最佳答案

您应该为您的类定义默认的无参数构造函数。 GSON 仅调用无参数构造函数来初始化类。你有一个带参数的构造函数,这就是它不被调用的原因;它创建一个ObjectConstructor来初始化。试试这个:

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

关于java - 从 json 字符串解析时未调用对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com