2013-06-22 33 views
0

我有一個使用條形碼掃描程序庫的Android應用程序。所有工作都很好,直到我創建了一個在掃描完成後調用的活動。無法解析Android應用中的JSON數組

該活動使用此JSON數組:

<?php 
$barCodes = array(
array(
    "id" => 123456, 
    "format" => "upc_1" 
), 
array(
    "id" => 39123439, 
    "format" => "upc_2" 
), 
array(
    "id" => 12345670, 
    "format" => "upc_3" 
) 
); 

回波json_encode($條形碼); ? >

和解析這個JSONArray代碼:

String scanResult; 

    Intent intent = getIntent(); 
    scanResult = intent.getStringExtra("result"); 


HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://someAddress.php"); 


    try { 

    HttpResponse response = httpclient.execute(httppost); 
    String jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); 


    JSONObject object = new JSONObject(jsonResult); 

    JSONArray jArray = object.getJSONArray("barCodes"); 

    JSONObject json_data; 
    int id ; 
    String format ; 
    String ret_format[] = new String[jArray.length()]; 
    int ret_id[] = new int[jArray.length()]; 

    for(int i=0;i<jArray.length();i++){ 
     json_data = jArray.getJSONObject(i); 

     id = json_data.getInt("id"); 
     format = json_data.getString("format"); 

     ret_id[i] = id; 
     ret_format[i] = format; 
     } 


     int scanInt = Integer.parseInt(scanResult); 

     switch(scanInt) { 

     case 123456: 
      textView.setText(ret_id[0] + " - " + ret_format[0]); 
     break; 

     case 39123439: 
      textView.setText(ret_id[1] + " - " + ret_format[1]); 
     break; 

     case 12345670: 
      textView.setText(ret_id[2] + " - " + ret_format[2]); 
     break; 

     default: 
      textView.setText("Result doesn't match the codes available..."); 
     break; 

     } 

    } 
    catch (JSONException e) { 
    e.printStackTrace(); 
    } 
    catch (ClientProtocolException e) { 
    e.printStackTrace(); 
    } 
    catch (IOException e) { 
    e.printStackTrace(); 
    } 

} 

private StringBuilder inputStreamToString(InputStream is) { 
     String rLine = ""; 
     StringBuilder answer = new StringBuilder(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

     try { 
     while ((rLine = rd.readLine()) != null) { 
      answer.append(rLine); 
      } 
     } 

     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return answer; 
     } 

應用工作沒有錯誤,但它不顯示從switch語句的任何結果。我不知道問題在哪裏。這裏有人可能有同樣的問題,所以請幫助我。

謝謝。

+0

您scanResult沒有聲明。並且您希望它看起來如何,因爲您的商店ID值爲'ret_id' – MDMalik

+0

已聲明scanResult,請允許我編輯帖子。 – Saraz

+0

現在scanresult中存儲的值是什麼樣子,它可能是123456? – MDMalik

回答

1

我覺得你的JSON結構是無效的。

對此結構看

{"menu": { 
    "id": "file", 
    "value": "File", 
    "popup": { 
    "menuitem": [ 
     {"value": "New", "onclick": "CreateNewDoc()"}, 
     {"value": "Open", "onclick": "OpenDoc()"}, 
     {"value": "Close", "onclick": "CloseDoc()"} 
    ] 
    } 
}}

JSON是基於{},[]:,,

我堅持讓你檢查jArray = object.getJSONArray("barCodes");並嘗試打印日誌。像jArray.toString();

您將會確切知道陣列裏面有什麼。