【发布时间】:2019-03-25 10:20:54
【问题描述】:
我在字符串中得到一个空数组作为来自服务器的响应并在转换它 JsonObject 时得到 ClassCastException,因为它是一个空数组。这是代码sn-p。
final String errorMessage = IOUtils.toString(errorStream); // response is "[]"
if (isJson(errorMessage)) {
final JsonObject jsonResult = new Gson().fromJson(errorMessage, JsonObject.class);
throw new IOException(jsonResult.get("error").toString());
} else {
throw new IOException("Json response is" + errorMessage);
}
这里是isJson方法
public static boolean isJson(String Json) {
try {
new JSONObject(Json);
} catch (JSONException ex) {
try {
new JSONArray(Json);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
我应该添加一个检查来比较“[]”吗
if(isJson(errorMessage) && !errorMessage.equals("[]"))
或者还有其他更好的方法。
请指导。
谢谢,
【问题讨论】:
-
一个空的 json 数组应该仍然是一个 json 数组...如果你得到一个异常你能提供完整的 stacktracke 吗?
-
您不应该将可能是数组或对象的东西强制转换为
JsonObject。您应该将其转换为JsonElement。 -
如果您有对应于该响应的 java POJO,那么您可以使用 com.fasterxml.jackson.databind.ObjectMapper 将 json 字符串直接映射到该对象。我每次都用那个。只是根据我的经验提出的建议。 :)
-
检查 if(errorStream.length()==0){ // 做你的工作 }else{ // 做你的工作 }
标签: java gson classcastexception