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

后端 未结 6 1374
耶瑟儿~
耶瑟儿~ 2020-11-28 10:05

I\'m trying to get the type of the value stored in a JSONObject.

String jString = {\"a\": 1, \"b\": \"str\"};
JSONObject jObj = new JSONObject(         


        
6条回答
  •  旧巷少年郎
    2020-11-28 10:58

    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(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 implements Iterable {
        private Iterator iterator;
        public AsIterable(Iterator iterator) {
            this.iterator = iterator;
        }
        public Iterator iterator() {
            return iterator;
        }
    }
    

提交回复
热议问题