【问题标题】:Android: unable to retrieve data from jsonAndroid:无法从 json 中检索数据
【发布时间】:2012-07-12 06:04:08
【问题描述】:

我从上一个活动中获取某个事件的一个 id 到这个活动,并将这个 id 传递给当前活动中的 url,以获取该 url 中存在的城市名称。我的代码是..

String s = getIntent().getStringExtra("ar");

try{          
    HttpPost hpost = new HttpPost("xxxxxxxxxxxxxxxxx/id");
    HttpResponse response = login.client.execute(hpost);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("id", s));
    hpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    String re = EntityUtils.toString(response.getEntity());
    System.out.print(re);

    JSONObject root = new JSONObject(re);  
    eveState.setText(root.getString("cityname"));  
}
catch(Exception e){
    Log.e("exvcx", "error getting data" +e.toString());
}

我得到的例外是cityname 没有价值。我想我无法将 id 传递给这个 url..请告诉这是正确的方法吗?如果是,请提供问题的解决方案,否则请纠正我做错的地方。谢谢。

{"status":1,"response":[{"id":"73","name":"Dangerous","address":"Rydgggh","location":"Entry try","phnumber":"2467568","createdate":"2012-07-11 06:24:31","image":"4ffd626f021487.45227344.jpg","block":"n","deleted":"n","cityname":"Juneau","statename":"Alaska","interestname":"Comedy","username":"princeb","eventdate":"2012-07-13 15:45:29","formatteddate":"July 13, 2012"}],"imageWidth":1024,"imageHeight":1024}

【问题讨论】:

  • 你能提供你的json字符串吗?因为您可能会得到 json 数组或 json 对象,所以没有 json 我们无法帮助您。但是从您的异常中,您尝试访问 json 中不可用的 id。
  • 请提供上一个活动的代码,它正在启动这个活动。我们需要了解您如何将数据传递给此活动。
  • 这就是我从以前的活动中获取 id 的方式..Intent i = new Intent(searchevent.this, eventDetails.class); i.putExtra("ar", id); startActivity(i);

标签: android json http-post httpresponse


【解决方案1】:

请参考我在以下问题中给出的答案

https://stackoverflow.com/a/11260845/1441666

我有这个数组

{
"result": "success",
"countryCodeList":
[
  {"countryCode":"00","countryName":"World Wide"},
  {"countryCode":"kr","countryName":"Korea"}
] 
}

下面我正在获取国家/地区详细信息

JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);

JSONArray valArray1 = valArray.getJSONArray(1);

valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");

int len = valArray1.length();

for (int i = 0; i < valArray1.length(); i++) {

 Country country = new Country();
 JSONObject arr = valArray1.getJSONObject(i);
 country.setCountryCode(arr.getString("countryCode"));                        
 country.setCountryName(arr.getString("countryName"));
 arrCountries.add(country);
}

【讨论】:

  • 07-12 12:11:02.441: ERROR/exvcx(3273): error getting dataorg.json.JSONException: Value 0 at 1 of type java.lang.Integer cannot be converted to JSONArray
  • JSONObject json = new JSONObject(re); JSONArray nameArray = json.names(); JSONArray valArray = json.toJSONArray(nameArray); JSONArray valArray1 = valArray.getJSONArray(1); valArray1.toString().replace("[", ""); valArray1.toString().replace("]", ""); int len = valArray1.length(); for (int i = 0; i &lt; valArray1.length(); i++) { JSONObject arr = valArray1.getJSONObject(i); eveNam.setText(arr.getString("cityname")); }
  • 在这段代码中,您在哪一行得到了上述错误?你上面提到的json响应字符串是正确的吗?
  • 是的,响应字符串是正确的。并在JSONArray valArray1 = valArray.getJSONArray(1); 上出现错误
  • JSONArray valArray1 = valArray.getJSONArray(0);而不是 1 写 0 这将解决您的问题
【解决方案2】:

我注意到的问题是:

  • 您在执行 HTTPPost 请求后设置了id 参数。
  • 未从服务器输入流中读取响应。您是否尝试将读取的数据打印到控制台并验证它是正确的。

使用下面的读取功能

public static JSONObject read(String url, String id){

    InputStream is = null;
    String result = "";
    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("id", id));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    JSONObject jsonObject=null;
    try {
        jsonObject = new JSONObject(result);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}
  • 现在您将获得封装在 JSONObject 中的 JSON 字符串
  • 现在遍历这个对象得到cityname

代码示例

try {
    JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = jsonObject.optJSONArray("response");
    String cityName = ((JSONObject)jsonArray.get(0)).getString("cityname");
    System.out.println("Cityname : "+cityName);
} catch (JSONException e2) {
    e2.printStackTrace();
}

【讨论】:

  • @downvoter 我可以知道这个downvote的原因,以便我知道这个问题
猜你喜欢
  • 2016-06-04
  • 2018-04-06
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2020-01-09
  • 1970-01-01
相关资源
最近更新 更多