gpt4 book ai didi

java - Android 上使用 GSON 解析 JSON

转载 作者:行者123 更新时间:2023-12-01 11:35:23 25 4
gpt4 key购买 nike

我已成功解析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 的简单方法

关于java - Android 上使用 GSON 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com