Haritha R
Haritha R

Reputation: 105

Issue in converting String to JSONArray/JSONObject

I have to check whether the given value is JSONObject or not.... example input :

Object obj = "{} testing"

i am checking with below code:

public boolean isJSONValid(Object obj) {
 try {
   new JSONObject(obj);
 } catch(JSONException e) {
   return false;
 }
 return true;
}

but for above input it is giving true, am using org.json jar file.

Upvotes: 0

Views: 243

Answers (2)

Daniël J
Daniël J

Reputation: 107

To check if an object is a JSONObject use instanceof.

if(obj instanceof JSONObject){
  //your code here
}

You can test if a String is valid JSON using: How to check whether a given string is valid JSON in Java But I'm assuming you already found that, looking at the similar code.


EDIT

This function returns false when given obj = "{} testing";

public boolean isJSONObject(Object obj) {
    if(obj instanceof JSONObject){
        return true;
    }
    return false;
}

Upvotes: 1

E_Denlinger
E_Denlinger

Reputation: 48

Can you print the "new JSONOBJECT(obj)" to string after you create it? I would think it is using reflection to convert that standard object to a JSON object when you are passing it to the constructor. Reference the answer to this question. It shows how to check if an object is an instance of a JSONObject.

Upvotes: 0

Related Questions