0

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.

2

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I've added a piece of code that does in fact return the correct value for your problem using instanceof.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.