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

JavaJson

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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
}

Solution 2 - Java

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

Solution 3 - Java

Please note that JSONObject.get() may return an integer as either java.lang.Integer or java.lang.Long, for example, for {a:3,b:100300000000} we see

D/+++     ( 5526): +++a=>class java.lang.Integer:3
D/+++     ( 5526): +++b=>class java.lang.Long:100300000000

I use the code like (note that we use types long and double instead of int and float, and that in my task there may be no nested JSONObject or JSONArray so they are not supported):

    for (String k : new AsIterable<String>(json.keys())) {
            try {
                    Object v = json.get(k);
		//Log.d("+++","+++"+k+"=>"+v.getClass()+":"+v);
                    if (v instanceof Integer || v instanceof Long) {
                            long intToUse = ((Number)v).longValue();
                            ...
                    } else if (v instanceof Boolean) {
                            boolean boolToUse = (Boolean)v).booleanValue();
                            ...
                    } else if (v instanceof Float || v instanceof Double) {
                            double floatToUse = ((Number)v).doubleValue();
                            ...
                    } else if (JSONObject.NULL.equals(v)) {
                            Object nullToUse = null;
                            ...
                    } else {
                            String stringToUse = json.getString(k);
                            ...
                    }
            } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    Log.d("exc: "+e2);
                    e2.printStackTrace();
            }
    }

where AsIterable lets us use the for(:) loop with an iterator and is defined as:

public class AsIterable<T> implements Iterable<T> {
	private Iterator<T> iterator;
	public AsIterable(Iterator<T> iterator) {
		this.iterator = iterator;
	}
	public Iterator<T> iterator() {
		return iterator;
	}
}

Solution 4 - Java

I found this way to find data type of element value in JSON / Json. It's working very fine for me.

JSONObject json = new JSONObject(str);
                Iterator<String> iterator = json.keys();

                if (iterator != null) {
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        Object value = json.get(key);
                        String dataType = value.getClass().getSimpleName();

                        if (dataType.equalsIgnoreCase("Integer")) {
                            Log.i("Read Json", "Key :" + key + " | type :int | value:" + value);

                        } else if (dataType.equalsIgnoreCase("Long")) {
                            Log.i("Read Json", "Key :" + key + " | type :long | value:" + value);

                        } else if (dataType.equalsIgnoreCase("Float")) {
                            Log.i("Read Json", "Key :" + key + " | type :float | value:" + value);

                        } else if (dataType.equalsIgnoreCase("Double")) {
                            Log.i("Read Json", "Key :" + key + " | type :double | value:" + value);

                        } else if (dataType.equalsIgnoreCase("Boolean")) {
                            Log.i("Read Json", "Key :" + key + " | type :bool | value:" + value);

                        } else if (dataType.equalsIgnoreCase("String")) {
                            Log.i("Read Json", "Key :" + key + " | type :string | value:" + value);

                        }
                    }
                }

Solution 5 - Java

You can parse all the data as String and then try to convert it to the desired type. At this point you may catch the exception and determine which type is the parsed data.

Solution 6 - Java

instanceof is not working for me. In the latest version to get the data type of the field dynamically, instead of using JSONObject.get what you can do is get it as JsonPrimitive like

JsonPrimitive value = json.getAsJsonPrimitive('key');

Now you can call

value.isNumber() value.isBoolean() value.isString()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUngureanu LiviuView Question on Stackoverflow
Solution 1 - JavaRahulView Answer on Stackoverflow
Solution 2 - JavaBobTheBuilderView Answer on Stackoverflow
Solution 3 - Java18446744073709551615View Answer on Stackoverflow
Solution 4 - JavaSandipkumar SavaniView Answer on Stackoverflow
Solution 5 - JavaEmil AdzView Answer on Stackoverflow
Solution 6 - JavaAhmed Nawaz KhanView Answer on Stackoverflow