2012-04-15 99 views
57

我是新來的JSON和嘗試本教程: http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/#comments獲取沒有數組名稱的JSONArray?

我是新來的JSON,C語言,Java和Android的同時,但我學習。本教程使用我稱爲命名數組的內容,但是我將在我的Android項目中使用的所有JSON將使用沒有命名數組的簡單錶行。下面是我使用的JSON和本教程中的地震json的示例。

通過地震陣列教程迭代,並轉換成使用下面的代碼的Java HashMap的列表:

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);    
} 

我的問題是,我該如何使用json.getJSONArray("")如果我的JSON只是簡單如下?我可以轉換剩下的代碼,我只需要知道如何使用getJSONArray("strJsonArrayName")加載該JSON,如果我沒有strJsonArrayName

我的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 
    } 
] 

教程的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 
    } 
    ] 
} 

在本教程中,基於來自@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; 
} 
} 

回答

117

你並不需要調用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);    
} 

不能使用完全相同的方法,在本教程中,因爲你處理的需求JSON在根部,而不是一個JSONObject分析爲JSONArray

+1

好吧,我明白了。我將getJSONObject方法轉換爲像這樣的getJSONArray方法,並將httpPost更改爲httpGet,現在它正在工作!謝謝! – Ricky 2012-04-15 19:04:44

+0

簡單而有用...謝謝!!! – dd619 2013-12-17 06:53:28

+0

你能告訴我這是什麼結果描述?JSONArray json = new JSONArray(result); – Sharath 2015-07-28 07:39:56

2

JSONArray有一個構造,這需要String源(假定是陣列)。

因此,像這樣

JSONArray array = new JSONArray(yourJSONArrayAsString); 
+0

完全是,但我的JSON沒有一個數組名。我在你的JSONArrayAsString中放什麼?你是說我應該只傳遞我的整個JSON輸出字符串作爲參數? – Ricky 2012-04-15 18:26:22

+0

好的,我想我明白你的意思了,請確認一下:我用你提到的新JSONArray作爲參數而不是「地震」 – Ricky 2012-04-15 18:27:37

+0

@Ricky不太對。你需要'getJSONfromURL()'方法返回一個'JSONArray',而不是'JSONObject'。 – 2012-04-15 18:30:40

0

我假定一個名爲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; 

}

0

這裏是下19API LVL一個解決方案:

所有的
  • 第一。製作一個Gson對象。 - >Gson gson = new Gson();

  • 第二步是StringRequest(而不是 JsonObjectRequest)

  • 的最後一步得到JsonArray讓您jsonObj作爲字符串...

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