【发布时间】: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