2013-07-22 25 views
3

我是android開發新手。我有以下的Android代碼來調用JSON如何在Android中調用JSON對象

try { 

     JSONObject jsonObject = new JSONObject(result); 
     //JSONObject object = jsonObject.getJSONObject("CUSTOMER_ID"); 
     JSONArray jArray = new JSONArray(CUSTOMER_ID); 
     returnUsername1 = jArray.getInt("CUSTOMER_ID"); 
     Toast.makeText(getApplicationContext(), ""+returnUsername1,Toast.LENGTH_LONG).show(); 
     for (int i = 0; i < jArray.length(); i++) { 
} 

我的JSON格式是這樣[[{"0":"1","CUSTOMER_ID":"1"}]]

我指的是一些json格式,它應該喜歡[{"0":"1","sno":"1"}]我可以理解這一點。但我的不同於此。

如何使用上面的代碼調用customer_id。任何人都可以提出解決方案。

+0

我有和你一樣的問題。 – Aravin

+0

爲什麼這個雙數組,如果你不需要它? –

+0

http://jsonviewer.stack.hu/。在線JSON查看器。 – Raghunandan

回答

1

你有什麼是JSON數組

JSONArray jsonarray = new JSONArray(result); // result is a Array 

[表示JSON數組節點

{代表JSON對象節點

您的JSON。你需要兩次Json數組嗎?

[ // array 
    [ //array 
     { // object 
      "0": "1", 
      "CUSTOMER_ID": "1" 
     } 
    ] 
    ] 

解析

JSONArray jsonArray = new JSONArray(result); 
JSONArray ja= (JSONArray) jsonArray.get(0); 
JSONObject jb = (JSONObject) ja.get(0); 
String firstvalue = jb.getString("0"); 
String secondvalue = jb.getString("CUSTOMER_ID"); 
Log.i("first value is",firstvalue); 
Log.i("second value is",secondvalue); 

logcat的

07-22 14:37:02.990: I/first value is(6041): 1 
07-22 14:37:03.048: I/second value is(6041): 1 
+0

我有一個疑問,你能幫助我嗎? – Vini

+0

@ user2607115這是什麼?如果我知道我會幫助一定。 – Raghunandan

+0

在同一個json我的網頁返回完整內容(我在php中使用header),它包含標籤如何避免這種情況,並返回只有json數組。 – Vini

0

一般情況下,從一個JSONArray得到一個JSONObject:

JSONObject jsonObject = jsonArray.getJSONObject(0); //0 -> first object 

然後

int userID = jsonObject.getInt("CUSTOMER_ID"); 
0

在這種情況下CUSTOMER_ID不被視爲JSONObject。如果把JSONObject是它是你的想法,那麼你應該能夠jsonObject.getString訪問它(「CUSTOMER_ID」)

0

試試這個

JSONObject jsonObject = new JSONObject(result); 
JSONArray jArray =json.getJSONArray("enterjsonarraynamehere"); 

for (int i=0; i < jArray.length(); i++) 
{ 
    try { 
     JSONObject oneObject = jArray.getJSONObject(i); 
     // Pulling items from the array 
     String cust= oneObject.getString("CUSTOMER_ID"); 
    } catch (JSONException e) { 
     // Oops something went wrong 
    } 
} 

林假設你的JSON是這樣

<somecode> 
    { 
     "enterjsonarraynamehere": [ 
      { "0":"1", 
       "CUSTOMER_ID":"1" 
      }, 
      { "0":"2", 
       "CUSTOMER_ID":"2" 
      } 
     ], 
     "count": 2 
    } 
<somecode> 
0

如果您對您的JSON任何問題格式首先通過本網站進行驗證 http://jsonlint.com/

然後用於解析

JSONObject jsonObject = new JSONObject(result); 
// since your value for CUSTOMER_ID in your json text is string then you should get it as 
// string and then convert to an int 
returnUsername1 = Integer.parseInt(jsonObject.getString("CUSTOMER_ID"));