質問

As straightforward we can check a given string is a proper JSON format or not? as we can use

http://jsonlint.com/

http://jsonviewer.stack.hu/ etc etc.

but if the same task we wants to do programatically how we can write a validator method in android as presently what I am trying to use is as follows.

Is this a proper way to achieve this, as I wrote the given function

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

please suggest if there is something better. these all things i need to check for test cases as i know services will take care of correct json.

役に立ちましたか?

解決

Try this..

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

他のヒント

this may help you,

public boolean isJSONValid(String test)
{
    try {
        new JSONObject(test);
        return true;
} catch(JSONException ex) { 
    return false;
   }
}

I think you should check it following way,

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;
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top