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.

Haritha R
  • 115
  • 1
  • 5
  • 16
  • I think this question is quite similar to this one: [How to check if a string is a valid JSON string in JavaScript without using Try/Catch](http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try). You might use the regular expression suggested or also `JSON.parse(str);` alternative with try/catch – Marcio Jasinski Oct 07 '15 at 14:20
  • Thank you, i will try using regular expression. – Haritha R Oct 07 '15 at 14:29

2 Answers2

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;
}
Community
  • 1
  • 1
Daniël J
  • 107
  • 10
  • I've added a piece of code that does in fact return the correct value for your problem using `instanceof`. – Daniël J Oct 07 '15 at 20:36
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.

Community
  • 1
  • 1