【问题标题】:getJSONObject returns wrong valuegetJSONObject 返回错误值
【发布时间】:2015-02-21 00:53:45
【问题描述】:

我正在使用返回 JSON 的 REST Web 服务。但是 JSON 对象的值是

“[12]”

当我打印时。该值必须只有12 没有"[]"

我的代码错了吗? 这是我的代码:

 HttpClient httpClient = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://applocalize.com.br/rest/rest.php");

                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("pg","categorias"));
                    nameValuePairs.add(new BasicNameValuePair("serv","buscar"));
                    nameValuePairs.add(new BasicNameValuePair("dt_atualizacao","0"));
                    try{
                        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    }catch (UnsupportedEncodingException e){

                    }

                    HttpResponse resp = httpClient.execute(post);
                    String respStr = EntityUtils.toString(resp.getEntity());

                    if (resp.getStatusLine().getStatusCode() == 200)
                    {
                        System.out.println(respStr);
                        JSONArray temp1 = new JSONArray(respStr);
                        for (int i=0; i < temp1.length(); i++) {
                            JSONObject obj = temp1.getJSONObject(i);
                            System.out.println(obj.getString("id"));
                        }


                    }
                    System.out.println("OKAY!");
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

当我打印 id 时有我的 logcat

02-20 13:45:32.560  31135-31135/com.localizeapp I/System.out﹕ ["52"]
02-20 13:45:32.560  31135-31135/com.localizeapp I/System.out﹕ ["53"]
02-20 13:45:32.560  31135-31135/com.localizeapp I/System.out﹕ ["54"]

编辑:

respStr:

02-20 13:45:32.210 31135-31135/com.allapps.localizeapp I/System.out﹕[{"id":["51"],"titulo":["Chaveiro"],"icone ":["这里是 64 进制......太长了"]

【问题讨论】:

  • 这不是解析器的错。你可以发布json吗?
  • System.out.println(respStr); 行中有哪些数据?
  • 我认为你里面有一个 json 数组。
  • 只是进行字符串替换是一种选择吗?你可以发布你的json吗? json 是否经过验证? obj.getString("id")[0]?
  • idJSONArray

标签: java android


【解决方案1】:

问题是您的 Web 服务将值返回为 JSONArrays。您可以更改网络服务以发送数据为

"id":"51"

或者你可以替换

System.out.println(obj.getString("id"));

System.out.println(obj.getJSONArray("id").get(0));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2015-06-19
    • 2014-01-16
    • 2019-10-13
    • 2020-10-05
    • 2015-11-19
    • 2020-05-27
    • 2017-04-16
    相关资源
    最近更新 更多