简体   繁体   中英

parsing of JSON with GSON on Android

I've successfully parsed http://kylewbanks.com/rest/posts this data into my Android application.

This JSON takes the format of

[
{...},
{...},
{...}
]

My issue is that I need to parse JSON in the format of

{
"count":3,
"result":[
{...},
{...},
{...}
]
}

I'm aware that I need to get past the count and result and only parse the arraylist. Any idea on how to do that with GSON. Do I need to loop to find it? Or is there another way?

My doInBackground

    @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 = new ArrayList<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;
    }
JSONArray notificationsArray = response.getJSONArray("array_name");
Model_Name[] model_name = new Gson().fromJson(notificationsArray.toString(), Model_Name[].class);

Easy way to parse JSON using GSON

You should create class to wrap whole structure eg.

class Result {
    private int count;
    private Post[] posts;
    // getters,setters
}

and instead of

 posts = Arrays.asList(gson.fromJson(reader, Post[].class));

write

result = gson.fromJson(reader, Result.class)

than get the array from result object

Read your object as a basic JsonObject , then get the JsonElement named "result", and pass that to gson:

JsonObject root = new JsonParser().parse(reader).getAsJsonObject();
JsonElement results = root.get("result");
Post[] posts = gson.fromJson(results, Post[].class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM