确定JSON是JSONObject还是JSONArray

问题描述 投票:113回答:8

我将从服务器接收JSON对象或数组,但我不知道它将是什么。我需要使用JSON,但为了这样做,我需要知道它是Object还是Array。

我正在使用Android。

有没有人有这样做的好方法?

android arrays json object
8个回答
217
投票

我找到了更好的方法来确定:

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  //you have an object
else if (json instanceof JSONArray)
  //you have an array

tokenizer能够返回更多类型:http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()


52
投票

有几种方法可以做到这一点:

  1. 您可以检查String的第一个位置处的字符(在删除空格之后,因为它在有效的JSON中是允许的)。如果它是{,你正在处理JSONObject,如果它是[,你正在处理JSONArray
  2. 如果您正在处理JSON(Object),那么您可以进行instanceof检查。 yourObject instanceof JSONObject。如果yourObject是JSONObject,则返回true。这同样适用于JSONArray。

12
投票

这是我在Android上使用的简单解决方案:

JSONObject json = new JSONObject(jsonString);

if (json.has("data")) {

    JSONObject dataObject = json.optJSONObject("data");

    if (dataObject != null) {

        //Do things with object.

    } else {

        JSONArray array = json.optJSONArray("data");

        //Do things with array
    }
} else {
    // Do nothing or throw exception if "data" is a mandatory field
}

4
投票

提出另一种方式:

if(server_response.trim().charAt(0) == '[') {
    Log.e("Response is : " , "JSONArray");
} else if(server_response.trim().charAt(0) == '{') {
    Log.e("Response is : " , "JSONObject");
}

这里server_response是来自服务器的响应字符串


1
投票

我的方法将完全从中抽象出来。也许有人觉得这很有用......

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class SimpleJSONObject extends JSONObject {


    private static final String FIELDNAME_NAME_VALUE_PAIRS = "nameValuePairs";


    public SimpleJSONObject(String string) throws JSONException {
        super(string);
    }


    public SimpleJSONObject(JSONObject jsonObject) throws JSONException {
        super(jsonObject.toString());
    }


    @Override
    public JSONObject getJSONObject(String name) throws JSONException {

        final JSONObject jsonObject = super.getJSONObject(name);

        return new SimpleJSONObject(jsonObject.toString());
    }


    @Override
    public JSONArray getJSONArray(String name) throws JSONException {

        JSONArray jsonArray = null;

        try {

            final Map<String, Object> map = this.getKeyValueMap();

            final Object value = map.get(name);

            jsonArray = this.evaluateJSONArray(name, value);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

        return jsonArray;
    }


    private JSONArray evaluateJSONArray(String name, final Object value) throws JSONException {

        JSONArray jsonArray = null;

        if (value instanceof JSONArray) {

            jsonArray = this.castToJSONArray(value);

        } else if (value instanceof JSONObject) {

            jsonArray = this.createCollectionWithOneElement(value);

        } else {

            jsonArray = super.getJSONArray(name);

        }
        return jsonArray;
    }


    private JSONArray createCollectionWithOneElement(final Object value) {

        final Collection<Object> collection = new ArrayList<Object>();
        collection.add(value);

        return (JSONArray) new JSONArray(collection);
    }


    private JSONArray castToJSONArray(final Object value) {
        return (JSONArray) value;
    }


    private Map<String, Object> getKeyValueMap() throws NoSuchFieldException, IllegalAccessException {

        final Field declaredField = JSONObject.class.getDeclaredField(FIELDNAME_NAME_VALUE_PAIRS);
        declaredField.setAccessible(true);

        @SuppressWarnings("unchecked")
        final Map<String, Object> map = (Map<String, Object>) declaredField.get(this);

        return map;
    }


}

现在永远摆脱这种行为......

...
JSONObject simpleJSONObject = new SimpleJSONObject(jsonObject);
...

1
投票

这样做的一个更基本的方法如下。

JsonArray天生就是List

JsonObject天生就是Map

if (object instanceof Map){
    JSONObject jsonObject = new JSONObject();
    jsonObject.putAll((Map)object);
    ...
    ...
}
else if (object instanceof List){
    JSONArray jsonArray = new JSONArray();
    jsonArray.addAll((List)object);
    ...
    ...
}

0
投票

的instanceof

Object.getClass()的getName()


0
投票

对于那些在JavaScript中处理这个问题的人来说,以下是我的工作(不确定它的效率)。

if(object.length != undefined) {
   console.log('Array found. Length is : ' + object.length); 
} else {
 console.log('Object found.'); 
}
© www.soinside.com 2019 - 2024. All rights reserved.