【问题标题】:parsing of JSON with GSON on Android在 Android 上使用 GSON 解析 JSON
【发布时间】:2015-05-05 14:08:35
【问题描述】:

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

此 JSON 采用以下格式

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

我的问题是我需要以

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

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

我的后台操作

    @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;
    }

【问题讨论】:

  • 琐碎:gson.fromJson(new JsonParser().parse(reader).getAsJsonObject().get("result"), Post[].class);

标签: java android json arraylist gson


【解决方案1】:
JSONArray notificationsArray = response.getJSONArray("array_name");
Model_Name[] model_name = new Gson().fromJson(notificationsArray.toString(), Model_Name[].class);

使用 GSON 解析 JSON 的简单方法

【讨论】:

  • 太丑了。解析json,然后重新格式化为json,然后重新解析?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    而不是

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

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

    比从结果对象中获取数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      相关资源
      最近更新 更多