【发布时间】:2014-12-10 07:34:36
【问题描述】:
我在用 gson 解析 json 时有一个奇怪的行为。我使用此代码:
private static Container parseContainer(String containerJson) {
try {
//TODO Remove try catch when Bug is done
return containerJson != null ? new Gson().fromJson(containerJson, Container.class)
: null;
} catch (JsonSyntaxException e) {
LOGGER.error("JsonSyntaxException ", e);
LOGGER.error("Json: " + containerJson);
//Sleep 3 minutes and try again.
try {
Thread.sleep(1000L * 60 * 3);
} catch (InterruptedException e1) {
LOGGER.error("Exception", e);
}
LOGGER.error("Try again to parse json: " + containerJson);
Container result = new Gson().fromJson(containerJson, Container.class);
LOGGER.error("Parsing successful on second try.");
return result;
}
}
在我的项目中调用该方法时,它通常可以正常工作而不会引发异常。但有时会抛出异常,等待一段时间后,解析工作正常。
我还没弄清楚什么时候抛出异常,什么时候不抛出。
如何记录“第二次尝试解析成功”的日志?
例外是
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapt erFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
【问题讨论】:
-
似乎在“第二次尝试解析成功”日志打印之前的 fromJson 调用中引发了异常。你能在这里显示一个失败的 JSON 吗?
-
在您尝试解析之前将 JSON 记录到 logcat 并在异常之前跟踪您尝试解析的确切数据 - 这样您就可以调试数据是否正确。您使用的后端可能存在错误。
-
你验证你的json了吗?您可以尝试使用此link 来验证您的 json
-
json 没问题。 3 分钟后生效(见示例代码)
标签: gson