Skip to content Skip to sidebar Skip to footer

Why Null Value Returns In Json Parsing In Android?

This is my Json: { 'feed': [ { 'id': '124124124124', 'source': 'aaaaaa', 'comment_count': 0, 'link': 'bbbbb',

Solution 1:

instead of giving inputstream directly to the GSON constructor, download the JSON string first from the URL and then pass it to the constructor for parsing as below:

String source = read(url);
Feed feeds=new Gson().fromJson(source ,Feed.class);
ArrayList<FeedResult>feed=new ArrayList<FeedResult>();
feed=feeds.getFeed();
for(FeedResult feedResult:feedResults)
    System.out.println(feedResult);

the read function:

publicstatic String read(String url){

    System.out.println("Connecting to service URL : "+url);
    InputStreamis=null;
    Stringresult="";
    // http posttry {
        HttpClienthttpclient=newDefaultHttpClient();
        HttpPosthttppost=newHttpPost(url);
        HttpResponseresponse= httpclient.execute(httppost);
        HttpEntityentity= response.getEntity();
        is = entity.getContent();

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

    // convert response to stringtry {
        BufferedReaderreader=newBufferedReader(newInputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuildersb=newStringBuilder();
        Stringline=null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();

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


    return result;
}

add toString() function in your FeedResult class, so that it will get printed to console in readable manner:

/* (non-Javadoc)
 * @see java.lang.Object#toString()
 */@OverridepublicStringtoString() {
    return"FeedResult [id=" + id + ", created_time=" + created_time
            + ", message=" + message + ", thumbnail=" + thumbnail
            + ", comment_count=" + comment_count + "]";
}

Post a Comment for "Why Null Value Returns In Json Parsing In Android?"