我该怎么解析android中的json?

时间:2015-03-01 16:23:00

标签: android json http android-webservice

当用户进入“沉默”状态时,我会这样做。在android中的edittextbox中,另一个文本框将显示这两个密码' umbrella'和' umbrella12'。 我试图通过这种类型的Json

{
   getValueResult: [
            {
               password: "umberlla"
               uname: "silent"
              },
            {
               password: "umberlla12" 
               uname: "silent"
              }]
}

解析json的代码如下。但是,在追加while循环后,我无法在StringBuilder中获取对象getValueResult,它显示为null。

这是我的安卓代码:

public void onGoClick(View v) 
    {
        EditText edt=(EditText)findViewById(R.id.editText1);
        HttpClient hc=new DefaultHttpClient();
        HttpPost hp=new HttpPost("http://192.168.0.4:80/WcfClassDatabase/Service1.svc/getValue");
        JSONObject jo=new JSONObject();
        try {
            jo.putOpt("name", edt);
            StringEntity se=new StringEntity(jo.toString());
            hp.setEntity(se);
            hp.setHeader("Accept","application/json");
            hp.setHeader("Content-type","application/json");
            HttpResponse hr= hc.execute(hp);
            Toast.makeText(this,"execute", Toast.LENGTH_LONG).show();

            HttpEntity he=hr.getEntity();
            InputStream is=he.getContent();
            InputStreamReader ir=new InputStreamReader(is);
            BufferedReader br=new BufferedReader(ir);
            StringBuilder sbr=new StringBuilder();
            String line="";
            while((line=br.readLine()) != null)
            {               
                sbr.append(line);
            }

            JSONObject job=new JSONObject(sbr.toString());
            JSONArray ja=job.getJSONArray("getValueResult:");
    //      ArrayList<String> al = new ArrayList<String>();

            String string=  ja.getJSONObject(0).getString("password");
            EditText edt2=(EditText)findViewById(R.id.editText2);
            edt2.setText(string);
        } 
        catch (Exception e) {
            // TODO Auto-generated catch block
            Toast.makeText(this, "oh!Failure", 10).show();
            e.printStackTrace();
        }

    }

我总是在调试时看到作业对象为null。

1 个答案:

答案 0 :(得分:1)

 { getValueResult: [2] 0: { password: "umberlla" uname: "silent" } 
1: { password: "umberlla12" uname: "silent" } }

这不是一个合适的json。首先确认json