Android 获取没有数组名称的 JSONArray?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10164741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:42:57  来源:igfitidea点击:

Get JSONArray without array name?

androidarraysjson

提问by Ricky

I'm new to JSON and trying this tutorial: http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/#comments

我是 JSON 新手,正在尝试本教程:http: //p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/#comments

I'm new to JSON, C languages, Java and also Android, but am learning. The tutorial uses what I'm calling a named array, but all of the JSON i'm going to be using in my android project will use simple table rows with no named array. Examples of the JSON i'm using and the earthquake json from the tutorial are below.

我是 JSON、C 语言、Java 和 Android 的新手,但我正在学习。本教程使用我所说的命名数组,但我将在我的 android 项目中使用的所有 JSON 都将使用没有命名数组的简单表行。我正在使用的 JSON 示例和教程中的地震 json 示例如下。

The tutorial iterates through the earthquake array and converts into a JAVA hashmap list using the following code:

本教程遍历地震数组并使用以下代码转换为 JAVA 哈希图列表:

JSONArray  earthquakes = json.getJSONArray("earthquakes");
    for(int i=0;i<earthquakes.length();i++){                        
        HashMap<String, String> map = new HashMap<String, String>();    
        JSONObject e = earthquakes.getJSONObject(i);

        map.put("id",  String.valueOf(i));
        map.put("name", "Earthquake name:" + e.getString("eqid"));
        map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
        mylist.add(map);            
}

My question is, how can I use json.getJSONArray("")if my JSON is just simple as below? I can convert the rest of the code, I just need to know how to load that JSON using the getJSONArray("strJsonArrayName")if I don't have a strJsonArrayName.

我的问题是,json.getJSONArray("")如果我的 JSON 如下所示,我该如何使用?我可以转换代码的其余部分,我只需要知道这样的JSON使用加载getJSONArray("strJsonArrayName"),如果我没有strJsonArrayName

My JSON (UnNamed Array)

我的 JSON(未命名数组)

[
  {
    "cnt":1,
    "name":"American",
    "pk":7
  },
  {
    "cnt":2,
    "name":"Celebrities",
    "pk":3
  },
  {
    "cnt":1,
    "name":"Female",
    "pk":2
  },
  {
    "cnt":1,
    "name":"Language",
    "pk":8
  },
  {
    "cnt":1,
    "name":"Male",
    "pk":1
  },
  {
    "cnt":1,
    "name":"Region",
    "pk":9
  }
]

Tutorial's JSON (Named Array)

教程的 JSON(命名数组)

{
  "earthquakes":[
    {
      "eqid":"c0001xgp",
      "magnitude":8.8,
      "lng":142.369,
      "src":"us",
      "datetime":"2011-03-11 04:46:23",
      "depth":24.4,
      "lat":38.322
    },
    {
      "eqid":"c000905e",
      "magnitude":8.6,
      "lng":93.0632,
      "src":"us",
      "datetime":"2012-04-11 06:38:37",
      "depth":22.9,
      "lat":2.311
    },
    {
      "eqid":"2007hear",
      "magnitude":8.4,
      "lng":101.3815,
      "src":"us",
      "datetime":"2007-09-12 09:10:26",
      "depth":30,
      "lat":-4.5172
    },
    {
      "eqid":"c00090da",
      "magnitude":8.2,
      "lng":92.4522,
      "src":"us",
      "datetime":"2012-04-11 08:43:09",
      "depth":16.4,
      "lat":0.7731
    },
    {
      "eqid":"2007aqbk",
      "magnitude":8,
      "lng":156.9567,
      "src":"us",
      "datetime":"2007-04-01 18:39:56",
      "depth":10,
      "lat":-8.4528
    },
    {
      "eqid":"2007hec6",
      "magnitude":7.8,
      "lng":100.9638,
      "src":"us",
      "datetime":"2007-09-12 21:49:01",
      "depth":10,
      "lat":-2.5265
    },
    {
      "eqid":"a00043nx",
      "magnitude":7.7,
      "lng":100.1139,
      "src":"us",
      "datetime":"2010-10-25 12:42:22",
      "depth":20.6,
      "lat":-3.4841
    },
    {
      "eqid":"2010utc5",
      "magnitude":7.7,
      "lng":97.1315,
      "src":"us",
      "datetime":"2010-04-06 20:15:02",
      "depth":31,
      "lat":2.3602
    },
    {
      "eqid":"2009mebz",
      "magnitude":7.6,
      "lng":99.9606,
      "src":"us",
      "datetime":"2009-09-30 08:16:09",
      "depth":80,
      "lat":-0.7889
    },
    {
      "eqid":"2009kdb2",
      "magnitude":7.6,
      "lng":92.9226,
      "src":"us",
      "datetime":"2009-08-10 17:55:39",
      "depth":33.1,
      "lat":14.0129
    }
  ]
}

In the tutorial, based on the answers from @MДΓΓ БДLL and @Cody Caughlan , I was able to reformat the JSONFunctions.getJSONFromURL into a JSONArray instead of a JSONObject. Here is my modified working code, thank you!

在本教程中,根据@MДΓΓ БДLL 和@Cody Caughlan 的回答,我能够将 JSONFunctions.getJSONFromURL 重新格式化为 JSONArray 而不是 JSONObject。这是我修改后的工作代码,谢谢!

public class JSONfunctions {
public static JSONArray getJSONfromURL(String url){
    InputStream is = null;
    String result = "";
    JSONArray jArray = null;

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();

        jArray = new JSONArray(result);            
    return jArray;
}
}

回答by Matt Ball

You don't need to call json.getJSONArray()at all, because the JSON you're working with already isan array. So, don't construct an instance of JSONObject; use a JSONArray. This should suffice:

您根本不需要调用json.getJSONArray(),因为您正在使用的 JSON 已经一个数组。所以,不要构造JSONObject;的实例。使用JSONArray. 这应该足够了:

// ...
JSONArray json = new JSONArray(result);
// ...

for(int i=0;i<json.length();i++){                        
    HashMap<String, String> map = new HashMap<String, String>();    
    JSONObject e = json.getJSONObject(i);

    map.put("id",  String.valueOf(i));
    map.put("name", "Earthquake name:" + e.getString("eqid"));
    map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
    mylist.add(map);            
}

You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArrayat the root, not a JSONObject.

您不能使用与教程中完全相同的方法,因为您正在处理的 JSON 需要JSONArray在根解析为 a ,而不是JSONObject

回答by Cody Caughlan

JSONArrayhas a constructor which takes a Stringsource (presumed to be an array).

JSONArray有一个构造函数,它接受一个String源(假定是一个数组)。

So something like this

所以像这样

JSONArray array = new JSONArray(yourJSONArrayAsString);

回答by G O'Rilla

I've assumed a named JSONArray is a JSONObject and accessed the data from the server to populate an Android GridView. For what it is worth my method is:

我假设一个命名的 JSONArray 是一个 JSONObject 并从服务器访问数据以填充 Android GridView。我的方法值得一提的是:

private String[] fillTable( JSONObject jsonObject ) {
   String[] dummyData = new String[] {"1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7", };
  if( jsonObject != null ) {
      ArrayList<String> data = new ArrayList<String>();
      try {
          // jsonArray looks like { "everything" : [{}, {},] }
          JSONArray jsonArray = jsonObject.getJSONArray( "everything" );
          int number = jsonArray.length(); //How many rows have got from the database?
          Log.i( Constants.INFORMATION, "Number of ows returned:  " + Integer.toString( number ) );
                  // Array elements look like this
          //{"success":1,"error":0,"name":"English One","owner":"Tutor","description":"Initial Alert","posted":"2013-08-09 15:35:40"}
          for( int element = 0; element < number; element++ ) { //visit each element
             JSONObject jsonObject_local = jsonArray.getJSONObject( element );
             //  Overkill on the error/success checking
             Log.e("JSON SUCCESS", Integer.toString( jsonObject_local.getInt(Constants.KEY_SUCCESS) ) );
             Log.e("JSON ERROR", Integer.toString( jsonObject_local.getInt(Constants.KEY_ERROR) ) );
                if ( jsonObject_local.getInt( Constants.KEY_SUCCESS) == Constants.JSON_SUCCESS ) {
                   String name = jsonObject_local.getString( Constants.KEY_NAME );
                   data.add( name );
                   String owner = jsonObject_local.getString( Constants.KEY_OWNER );
                   data.add( owner );
                   String description = jsonObject_local.getString( Constants.KEY_DESCRIPTION );
                   Log.i( "DESCRIPTION", description );
                   data.add( description ); 
                   String date = jsonObject_local.getString( Constants.KEY_DATE );
                   data.add( date );
                }
                else {
                    for( int i = 0; i < 4; i++ ) {
                        data.add( "ERROR" );
                    }
                }
          }
  }  //JSON object is null
  catch ( JSONException jsone) {
      Log.e( "JSON EXCEPTION", jsone.getMessage() );
  }
      dummyData = data.toArray( dummyData );
  }
  return dummyData;

}

}

回答by Péter Hidvégi

Here is a solution under 19API lvl:

这是19API lvl下的解决方案:

  • First of all. Make a Gson obj. --> Gson gson = new Gson();

  • Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)

  • The last step to get JsonArray...
  • 首先。制作一个 Gson 对象。-->Gson gson = new Gson();

  • 第二步是使用 StringRequest(而不是 JsonObjectRequest)将您的 jsonObj 作为字符串

  • 获取 JsonArray 的最后一步...

YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);