【问题标题】:how can I parse json in android?如何在android中解析json?
【发布时间】:2015-03-01 16:22:59
【问题描述】:

当用户在 android 的 edittextbox 中输入“silent”时,另一个文本框将显示这两个密码“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();
        }

    }

在调试时看到作业对象为空。

【问题讨论】:

  • 你的 json 格式不正确,试试这个链接来检查 json 的验证 - jsonlint.com

标签: android json http android-webservice


【解决方案1】:
 { getValueResult: [2] 0: { password: "umberlla" uname: "silent" } 
1: { password: "umberlla12" uname: "silent" } }

这不是一个正确的 json。先确认json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 2014-05-10
    • 2015-10-24
    • 2011-07-30
    • 2017-04-08
    • 2013-01-26
    相关资源
    最近更新 更多