我正在处理格式不正确的 JSON 响应。所有字段都作为 Strings
返回。不幸的是,我无法控制返回数据。
我正在使用 Gson 并尝试解析包含如下字段的 JSON 对象:
{
[...]
"cost": "9.25"
}
它显然应该被打印成一个Number
。当我尝试将其解析为 String
、Number
或 double
时,我得到一个 NumberFormatException:
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException:
[...]
at com.myapp.android.LauncherActivity$1.onSuccess(LauncherActivity.java:69)
[...]
Caused by: java.lang.NumberFormatException:
at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:267)
at java.lang.Double.parseDouble(Double.java:285)
at com.google.gson.stream.JsonReader.nextInt(JsonReader.java:599)
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:228)
... 19 more
LauncherActivity 第 69 行:
Item item = gson.fromJson(response, Item.class);
所以我关注了this similar question并尝试像这样创建一个 TypeAdapter
:
public class CostTypeAdapter implements JsonDeserializer<Double>, JsonSerializer<Double> {
public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Double cost;
try {
cost = json.getAsDouble();
} catch (NumberFormatException e) {
cost = 0.00d;
}
return cost;
}
public JsonElement serialize(Double src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src);
}
}
并在创建GsonBuilder
时注册:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Cost.class, new CostTypeAdapter());
Gson gson = builder.create();
还有我的Cost
类:
public class Cost {
private Double value;
public Cost(Double value) {
this.value = value;
}
public Double getValue() {
return value;
}
}
但我得到了相同的 NumberFormatException
。
对这里发生的事情有什么想法吗?至少不应该在我的 CostTypeAdapter.deserialize()
中捕获此异常吗?
非常感谢任何帮助/指导。
最佳答案
您还可以使用 GsonBuilder
的 registerTypeAdapter()
来捕获可能的解析异常并按您希望的方式处理它们。
在解析 Float
时捕获 NumberFormatException
并使值为 null 的示例:
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(Float.class, new TypeAdapter<Float>() {
@Override
public Float read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String stringValue = reader.nextString();
try {
Float value = Float.valueOf(stringValue);
return value;
} catch (NumberFormatException e) {
return null;
}
}
@Override
public void write(JsonWriter writer, Float value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(value);
}
});
关于java - 将 String 转换为 double 时 GSON 中的 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239117/