我有一个带有一些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的自动转换?
答案 0 :(得分:1)
获得结果的最简单方法是使用一些辅助类:
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();
//...