解析从Android中的服务器获取的JSON字符串

时间:2012-11-30 09:01:36

标签: android json

我在Android上解析了Json数据的链接,但几乎不了解。 我从服务器获取以下JSON字符串。

我需要解析它并在我的Android应用程序中将其作为列表视图呈现。任何指导或代码段。? 此外,由于我的Jason字符串包含图像数据,listview是否能够正确显示它?

我的JSON字符串是:

{"results":{"result":[{"year":"2012","title":"The Amazing Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/i.media-imdb.com\/images\/SF1f0a42ee1aa08d477a576fbbf7562eed\/realm\/feature.gif"},

{"year":"2014","title":"The Amazing Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,0,54,74_.jpg"},

{"year":"2002","title":"Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Sam Raimi","rating":"6.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ@@._V1._SX54_CR0,0,54,74_.jpg"},

{"year":"2007","title":"Spider-Man 3","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"7.5","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ@@._V1._SX54_CR0,0,54,74_.jpg"},

{"year":"2004","title":"Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"6.8","cover":"http:\/\/i.media-imdb.com\/images\/SFa26455c07afc3c94f52e95de50d5d814\/realm\/tv_series.gif"}]}} 

2 个答案:

答案 0 :(得分:1)

制作所有字段的Arraylist并写下面的函数来解析json以上,它将解决你的问题。

ArrayList<String> year, title, details, director, rating, cover;
// For Parse Login Response From Server
public void mParseResponse() throws UnknownHostException { 

    year=new ArrayList<String>();
    title=new ArrayList<String>();
    details=new ArrayList<String>();
    director=new ArrayList<String>();
    rating=new ArrayList<String>();
    cover=new ArrayList<String>();

    try {
        JSONObject jObject = new JSONObject(EntityUtils.toString(entity));
        JSONObject jsonobjresults = jObject.getJSONObject("results");
        JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
        for(int i=0;i<jsonarrayresult.length(); i++){
            JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
            year.add(mJsonObj.getString("year"));
            title.add(mJsonObj.getString("title"));
            details.add(mJsonObj.getString("details"));
            director.add(mJsonObj.getString("director"));
            rating.add(mJsonObj.getString("rating"));
            cover.add(mJsonObj.getString("cover"));
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

阅读本教程http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

您可以使用Google的gson库来解析json。 你需要创建java类来存储json值 将类引用传递给gson libary。它有简单的方法。

chec this doc