在检索json数据时遇到问题。如何检索它

时间:2015-10-25 12:27:38

标签: android json parsing

基本上我正在尝试制作天气应用程序。我试图检索一些数据(比如说来自crood对象的lat和lon)但是每当我运行应用程序时它都没有向我显示任何错误,但它在logcat中显示一个异常,它表示"没有价值的crood& #34 ;.我已经尝试了我拥有的所有资源,但我无法将数据显示到textviews。

这是我想要定位的json

{"coord":{"lon":-0.13,"lat":51.51},"weather":      [{"id":721,"main":"Haze","description":"haze","icon":"50d"},     {"id":501,"main":"Rain","description":"moderate rain","icon":"10d"},  {"id":311,"main":"Drizzle","description":"rain and drizzle","icon":"09d"}],"base":"stations","main":{"temp":286.15,"pressure":1013,"humidity":87,"temp_min":286.15,"temp_max":286.15},"visibility":10000,"wind":{"speed":3.1,"deg":200},"clouds":{"all":75},"dt":1445700000,"sys":  {"type":1,"id":5089,"message":0.0153,"country":"GB","sunrise":1445668823,"sunset":1445705286},"id":2643743,"name":"London","cod":200}

我就是这样做的

            String finalJson=buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONObject jsonObject =parentObject.getJSONObject("crood");

如果有人帮我解释这个逻辑怎么解析它。我希望从这些数据中得到lat,lon,name,description,temp和pressure,我想在textviews中显示它。

3 个答案:

答案 0 :(得分:1)

问题是关键。我使用了错误的密钥。 :3 crood而不是coord

答案 1 :(得分:0)

  1. 创建模型,在set中声明你想要的东西并获得。
  2. 接下来创建arrayadapter并定位对象。
  3. 创建活动声明

    HttpClient client = new DefaultHttpClient();

                HttpGet request = new HttpGet("Url Json Url");
    
                HttpResponse response = client.execute(request);
    
                HttpEntity resEntity = response.getEntity();
    
                String json = EntityUtils.toString(resEntity);
    
                JSONArray jarray = new JSONArray(json);
    
                newsList = new ArrayList<NewsModel>();
    
                for (int i = 0; i < jarray.length(); i++)
    

    {

                    JSONObject row = jarray.getJSONObject(i);
    
                    NewsModel data = new NewsModel();
    
                    data.setTitle(row.getString("title"));
    
                    data.setContent(row.getString("content"));
    
                    data.setExcerpt(row.getString("excerpt"));
    
                    data.setDate(row.getString("date"));
    
                    data.setImage(row.getString("feature_image"));
    
                    newsList.add(data);
    

答案 2 :(得分:0)

下面创建模型
ublic class NewsModel implements Serializable{

String title;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getExcerpt() {
    return excerpt;
}

public void setExcerpt(String excerpt) {
    this.excerpt = excerpt;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

String content;
String excerpt;
String date;
String image;

}