在Asynctask中解析json,没有结果预期

时间:2014-01-16 15:43:59

标签: java json parsing android-asynctask

我正在尝试解析AsyncTask中的JSON,到目前为止一切正常,但没有告诉我希望的结果。

PHP代码:

  if($row>0){
$resultado["productos"][]=array("logstatus"=>$nombre);
 }
 else{
$resultado["productos"][]=array("logstatus"=>"0");
}
echo json_encode( $resultado );

结果:

{"productos":[{"logstatus":"nombre"}]}

JAVA CODE:

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
                    arraylist = new ArrayList<HashMap<String, String>>();
                    // Retrieve JSON Objects from the given URL address
                    jsonobject = JSONfunctions
                            .getJSONfromURL("url/file.php");

                    if(jsonobject != null){         
                    try {
                        // Locate the array name in JSON
                        jsonarray = jsonobject.getJSONArray("productos");
                        for (int i = 0; i < jsonarray.length(); i++) {
                            HashMap<String, String> map = new HashMap<String, String>();
                            jsonobject = jsonarray.getJSONObject(i);
                            // Retrive JSON Objects
                            map.put("logstatus", jsonobject.getString("logstatus"));
                            arraylist.add(map);
                        }

                    } catch (JSONException e) {
                        Log.e("Error", e.getMessage());
                        //e.printStackTrace();
                    } catch (Exception e) {
                        Log.e("Error", e.getMessage());         
                    }
                    }else{
                        //Log.e("Response","No data");
                    }
                    return null;
                }

    @Override
    protected void onPostExecute(Void args) {

        SymbolSet syms = scanner.getResults();
        for (Symbol sym : syms) {
            if("".equals(sym.getData())){
                Toast.makeText(getBaseContext(),"found", Toast.LENGTH_SHORT).show();    
                finish();
                barcodeScanned = true;
            }else{
                Toast.makeText(getBaseContext(),"Not found"+arraylist, Toast.LENGTH_SHORT).show();
            }
        }
        mProgressDialog.dismiss();          
    }

当您运行AsyncTask时,会显示Toast并显示以下消息:Not found = [{“logstatus”:“name”}],我需要删除[{}]并仅获取值“name”。

我怎么能得到那个结果?感谢所有

1 个答案:

答案 0 :(得分:0)

如果你在arraylist中总是有一个对象,你可以使用该代码:

Toast.makeText(getBaseContext(),"Not found" + arraylist.get(0).get("logstatus"), Toast.LENGTH_SHORT).show();