如何在Java中创建json对象之前检查空数组字符串? [英] How to check empty array string before creating json object in java?

查看:136
本文介绍了如何在Java中创建json对象之前检查空数组字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为服务器&的响应,我得到了一个空字符串数组在转换JsonObject时获取ClassCastException,因为它是一个空数组。这是代码段。

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);
}

这是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;
    }

我应该添加支票来比较 []吗

should i add a check to compare "[]" like

if(isJson(errorMessage) && !errorMessage.equals("[]"))

,否则可能还有其他更好的方法。

or there could be any other better way to do it.

请指导。

谢谢

推荐答案

您可以使用<$ c中的方法$ c>是* 家庭:

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);
    }
}

打印:

null
"Internal error"

没有必要检查 [] 字符串,因为方括号之间可能有许多不同的白色字符。 JsonElement 是所有 JSON 对象的根类型,并且可以安全使用。

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.

这篇关于如何在Java中创建json对象之前检查空数组字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆