0

很简单,我们可以检查给定的字符串是否是正确的 JSON 格式?我们可以使用

http://jsonlint.com/

http://jsonviewer.stack.hu/等等等等。

但是,如果我们想以编程方式执行相同的任务,我们如何在android中编写验证器方法,目前我正在尝试使用如下。

这是实现这一目标的正确方法吗,因为我编写了给定的函数

public boolean isJSONValid(String test) {

    try {
        new JSONObject(test);
        return true;
    } catch (JSONException ex) {
        try {
            new JSONArray(test);
            return true;
        } catch (JSONException ex1) {
            return false;
        }
    }
}

请建议是否有更好的东西。这些我需要检查测试用例的所有事情,因为我知道服务会处理正确的 json。

4

3 回答 3

3

尝试这个..

 try {
        Object obj = new JSONTokener(test).nextValue();

        if (obj instanceof JSONObject)
              //you have an object
        else if (obj instanceof JSONArray)
              //you have an array

    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
于 2014-04-03T05:41:06.880 回答
1

这可能会帮助你,

public boolean isJSONValid(String test)
{
    try {
        new JSONObject(test);
        return true;
} catch(JSONException ex) { 
    return false;
   }
}
于 2014-04-03T05:28:15.737 回答
0

我认为您应该按照以下方式检查它,

public boolean isJSONValid(String test) 
{
    try 
    {
        new JSONObject(test);
        // If JsonObject is ok then check for JSONArray
        try 
        {
            new JSONArray(test);
            return true;
        } catch (JSONException ex1) {
            return false;
        }
    } catch (JSONException ex) {
        try 
        {
            new JSONArray(test);
            return true;
        } catch (JSONException ex1) {
            return false;
        }
    }
}
于 2014-04-03T05:25:16.610 回答