2013-04-18 11 views
8

In Java, so che è possibile verificare se una chiave è presente con il metodo isNull(). C'è un modo per verificare quale tipo di dati contiene la chiave?Come può essere determinato il tipo di dati di una proprietà JSON?

Considerare i seguenti esempi.

vorrei una funzione come JSONBody.getDataType ("chiave") e sarebbe tornare stringa

{ 
    "key" : "value" 
} 

vorrei una funzione come JSONBody.getDataType ("chiave") e sarebbe tornare JSONObject

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

vorrei una funzione come JSONBody.getDataType ("chiave") e sarebbe tornare JSONArray

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

Vorrei una funzione come JSONBody.getDataType ("chiave") ed è booleano

{ 
    "key" : true 
} 

vorrei tornare fa qualcosa del genere esiste?

+1

Dai un'occhiata alla http://stackoverflow.com/questions/9844494/json-to-java-objects-best-practice-for-modeling-the-json-stream .... non c'è xsd;) – MemLeak

+2

L'esempio dell'array definisce (erroneamente) un oggetto JSON, non un array; è necessario cambiare le parentesi graffe per le parentesi quadre. –

+0

È possibile eseguire un IF else e utilizzare l'istanza di o uguale. Acquista questo thread: http://stackoverflow.com/questions/106336/how-do-i-find-out-what-type-each-object-is-in-a-aleylistobject – MasNotsram

risposta

6
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"); 
} 
+0

perfetto. Grazie – David

Problemi correlati