我已经成功解析了http://kylewbanks.com/rest/将此数据发布到我的Android应用程序中。
此JSON的格式为
[
{...},
{...},
{...}
]
我的问题是我需要以以下格式解析JSON:
{
"count":3,
"result":[
{...},
{...},
{...}
]
}
我知道我需要超越计数和结果,仅解析arraylist。关于如何使用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;
}
阅读您的对象作为基础JsonObject
,然后获取JsonElement
名为“ result”的结果,并将其传递给gson:
JsonObject root = new JsonParser().parse(reader).getAsJsonObject();
JsonElement results = root.get("result");
Post[] posts = gson.fromJson(results, Post[].class);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句