Reputation: 53
I've successfully parsed http://kylewbanks.com/rest/posts this data into my Android application.
This JSON takes the format of
[
{...},
{...},
{...}
]
My issue is that I need to parse JSON in the format of
{
"count":3,
"result":[
{...},
{...},
{...}
]
}
I'm aware that I need to get past the count and result and only parse the arraylist. Any idea on how to do that with GSON. Do I need to loop to find it? Or is there another way?
My 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;
}
Upvotes: 0
Views: 697
Reputation: 39386
Read your object as a basic JsonObject
, then get the JsonElement
named "result", and pass that to gson:
JsonObject root = new JsonParser().parse(reader).getAsJsonObject();
JsonElement results = root.get("result");
Post[] posts = gson.fromJson(results, Post[].class);
Upvotes: 0
Reputation: 854
You should create class to wrap whole structure eg.
class Result {
private int count;
private Post[] posts;
// getters,setters
}
and instead of
posts = Arrays.asList(gson.fromJson(reader, Post[].class));
write
result = gson.fromJson(reader, Result.class)
than get the array from result object
Upvotes: 0
Reputation: 3723
JSONArray notificationsArray = response.getJSONArray("array_name");
Model_Name[] model_name = new Gson().fromJson(notificationsArray.toString(), Model_Name[].class);
Easy way to parse JSON using GSON
Upvotes: 1