1

I am trying to develop my skills in json parsing. What i have found that i have to implement some kind of json parsing library as for example GSON. I have this json for my example here. And this is the code i am using to get the values from json:

private class PostFetcher extends AsyncTask<Void, Void, String> {
    private static final String TAG = "PostFetcher";
    public static final String SERVER_URL = "http://kylewbanks.com/rest/posts";

    @Override
    protected String doInBackground(Void... params) {
        try {
            //Create an HTTP client
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(SERVER_URL);

            //Perform the request and check the status code
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();

                try {
                    //Read the server response and attempt to parse it as JSON
                    Reader reader = new InputStreamReader(content);

                    GsonBuilder gsonBuilder = new GsonBuilder();
                    gsonBuilder.setDateFormat("M/d/yy hh:mm a");
                    Gson gson = gsonBuilder.create();
                    List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
                    content.close();

                    handlePostsList(posts);
                } catch (Exception ex) {
                    Log.e(TAG, "Failed to parse JSON due to: " + ex);
                    failedLoadingPosts();
                }
            } else {
                Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
                failedLoadingPosts();
            }
        } catch(Exception ex) {
            Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
            failedLoadingPosts();
        }
        return null;
    } 
}

What i am trying to find out whether is it possible to get data only from one json object by using ID. Is it possible or is it not and if it is possible could you please help me to understand it because i am in deadlock now and i cannot understand a lot of things from gson.

I have found that maybe there is something similar like this in gson?:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}
AndroidFreak
  • 866
  • 1
  • 10
  • 31
  • Similar question was answered at the following link; https://stackoverflow.com/questions/11428329/using-gson-to-deserialize-specific-json-field-of-an-object – AnandShanbhag Jun 01 '18 at 10:44

0 Answers0