I'm trying to get the type of the value stored in a JSONObject
.
String jString = {"a": 1, "b": "str"}; JSONObject jObj = new JSONObject(jString);
Is it possible to get the type of the value stored at key "a"
; something like jObj.typeOf("a") = java.lang.Integer
?
A JSONObject has few important methods to display the values of different types like getString() method to get the string associated with a key string, getInt() method to get the int value associated with a key, getDouble() method to get the double value associated with a key and getBoolean() method to get the boolean ...
JSONArray interventions; if(intervention == null) interventions=jsonObject. optJSONArray("intervention"); This will return you an array if it's a valid JSONArray or else it will give null .
JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.
You can get the object from the JSON with the help of JSONObject.get()
method and then using the instanceof
operator to check for the type of Object.
Something on these lines:-
String jString = "{\"a\": 1, \"b\": \"str\"}"; JSONObject jObj = new JSONObject(jString); Object aObj = jObj.get("a"); if (aObj instanceof Integer) { // do what you want }
The best solution is to use JSONObject.get()
and check for the type using instanceof
operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With