gpt4 book ai didi

java - 在java中使用fromJson时自动转换

转载 作者:行者123 更新时间:2023-12-01 13:01:56 24 4
gpt4 key购买 nike

我有一个带有一些 int 参数的类,我正在尝试使用 fromJson 将一些值加载到此类中。当参数为自然数时效果很好,但当参数非自然数时抛出异常。

代码示例:

public class WebElemetsPoss{
int screenWidth;
int screenHeight;
...
}

Gson gson = new Gson();
// value = {"screenWidth":360,"screenHeight":519.894, .... }
WebElemetsPoss wep = gson.fromJson(value, WebElemetsPoss.class);

有没有办法在使用 fromJson 时执行从 double 到 int 的自动转换?

最佳答案

获得结果的最简单方法是使用一些辅助类:

public class WebElemetsPoss {
int screenWidth;
int screenHeight;

public WebElemetsPoss(double screenWidth, double screenHeight) {
this.screenWidth = (int)screenWidth;
this.screenHeight = (int)screenHeight;
}

public WebElemetsPoss(DoubleLoader loader) {
this(loader.screenWidth, this.screenHeight);
}

public static class DoubleLoader {
double screenWidth;
double screenHeight;
}
}

....

Gson gson = new Gson();
WebElemetsPoss wep = new WebElemetsPoss(gson.fromJson(value, WebElemetsPoss.DoubleLoader.class));

另一种可能的解决方案是添加自定义类型适配器:

class WebElemetsPossAdapter extends TypeAdapter<WebElemetsPoss> {
@Override
public WebElemets read (JsonReader reader) throws IOException {
int screenWidth = 0, screenHeight = 0;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("screenWidth")) {
screenWidth = (int)reader.nextDouble();
} else if (name.equals("screenHeight")) {
screenHeight = (int)reader.nextDouble();
} else {
reader.skipValue();
}
}
reader.endObject();
return new WebElemets(screenWidth, screenHeight);
}

@Override
public void write(JsonWriter out, WebElemets value) throws IOException {
}
}

//...

Gson gson = new GsonBuilder().registerTypeAdapter(WebElemetsPoss.class, new WebElemetsPossAdapter()).create();
//...

关于java - 在java中使用fromJson时自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23454467/

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