Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the type of a value from a JSONObject?

Tags:

java

json

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?

like image 890
Ungureanu Liviu Avatar asked Apr 10 '13 08:04

Ungureanu Liviu


People also ask

How do you get the values of the different types from a JSON object in Java?

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 ...

How do I check if a String is JSON object or JSONArray?

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 .

What is data type for JSON in Java?

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.


2 Answers

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 } 
like image 136
Rahul Avatar answered Sep 29 '22 15:09

Rahul


The best solution is to use JSONObject.get() and check for the type using instanceof operator.

like image 22
BobTheBuilder Avatar answered Sep 29 '22 14:09

BobTheBuilder