问题
I'm getting an empty array in string as a response from server & getting ClassCastException while converting it JsonObject because it's an empty array. Here is code snippet.
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);
}
Here is isJson Method
public static boolean isJson(String Json) {
try {
new JSONObject(Json);
} catch (JSONException ex) {
try {
new JSONArray(Json);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
should i add a check to compare "[]" like
if(isJson(errorMessage) && !errorMessage.equals("[]"))
or there could be any other better way to do it.
Please guide.
Thanks,
回答1:
You can use method from is*
family:
Gson gson = new GsonBuilder().create();
String[] jsons = {"[]", "[ ]", "[\r\n]", "{}", "{\"error\":\"Internal error\"}"};
for (String json : jsons) {
JsonElement root = gson.fromJson(json, JsonElement.class);
if (root.isJsonObject()) {
JsonElement error = root.getAsJsonObject().get("error");
System.out.println(error);
}
}
prints:
null
"Internal error"
There is no point to check "[]"
string because between brackets could be many different white characters. JsonElement
is a root type for all JSON
objects and is safe to use.
回答2:
Try this
if(!errorMessage[0]==null)
If your array is empty at position 0, it is returned null, or if you declare the array size when you declare it to be done:
if(!errorMessage[0]=="")
来源:https://stackoverflow.com/questions/55335589/how-to-check-empty-array-string-before-creating-json-object-in-java