在 Android 上使用 GSON 解析 JSON

parsing of JSON with GSON on Android

我已成功将 http://kylewbanks.com/rest/posts 这些数据解析到我的 Android 应用程序中。

这个JSON采用

的格式
[
{...},
{...},
{...}
]

我的问题是我需要以

的格式解析 JSON
{
"count":3,
"result":[
{...},
{...},
{...}
]
}

我知道我需要跳过计数和结果,只解析数组列表。关于如何使用 GSON 做到这一点的任何想法。我需要循环才能找到它吗?或者有别的办法吗?

我的 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);

使用 GSON

解析 JSON 的简单方法

您应该创建 class 来包装整个结构,例如

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

而不是

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

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

比从结果对象获取数组

将您的对象作为基本 JsonObject 读取,然后获取名为 "result" 的 JsonElement,并将其传递给 gson:

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