Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the datatype of a JSON property be determined?

Tags:

java

json

In Java, I know you can check if a key is present with the isNull() method. Is there a way to check what kind of data the key holds?

Consider the following examples.

I would want a function like JSONBody.getDataType("key") and it would return String

{
    "key" : "value"
}

I would want a function like JSONBody.getDataType("key") and it would return JSONObject

{
    "key" : { 
        "parm1" : "value1",
        "parm2" : "value2"
    }
}

I would want a function like JSONBody.getDataType("key") and it would return JSONArray

{
    "key" : [
        "value1",
        "value2",
        "value3"
    ]
}

I would want a function like JSONBody.getDataType("key") and it would return Boolean

{
    "key" : true
}

Does something like this exist?

like image 966
David Avatar asked Apr 18 '13 14:04

David


1 Answers

JSONObject stuff = new JSONObject(whatever);
Object thing = stuff.get("key");
String classNameOfThing = thing.getClass().getName();
Systen.out.println("thing is a " + classNameOfThing);
if (thing instanceof Integer) {
    System.out.println("thing is an Integer");
} 
like image 92
Hot Licks Avatar answered Oct 13 '22 00:10

Hot Licks