0

我有一个使用条形码扫描仪库的 Android 应用程序。一切正常,直到我创建了一个在扫描完成后调用的 Activity。

该活动使用此 JSON 数组:

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

回声 json_encode($barCodes); ?>

解析这个 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 语句的任何结果。我不知道问题出在哪里。这里有人可能有同样的问题,所以请帮助我。

谢谢。

4

1 回答 1

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

你会确切地知道数组里面有什么。

于 2013-06-22T18:46:02.660 回答