How to check empty array string before creating json object in java?

微笑、不失礼 提交于 2019-12-11 18:29:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!