8

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?

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
David
  • 10,418
  • 17
  • 72
  • 122
  • 1
    Have a look at http://stackoverflow.com/questions/9844494/json-to-java-objects-best-practice-for-modeling-the-json-stream .... there is no xsd ;) – MemLeak Apr 18 '13 at 14:43
  • 2
    Your array example is (incorrectly) defining a JSON object, not an array; need to switch the curly braces for square brackets. – Anthony Grist Apr 18 '13 at 14:49
  • You can do an IF else, and use instance of or equals. Checkout this thread: http://stackoverflow.com/questions/106336/how-do-i-find-out-what-type-each-object-is-in-a-arraylistobject – MasNotsram Apr 18 '13 at 14:57
  • Parse it into a Map, retrieve the item as an Object, and test its class. – Hot Licks Apr 18 '13 at 15:19

1 Answers1

8
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");
} 
Hot Licks
  • 47,103
  • 17
  • 93
  • 151