Just use Retrofit and GSON
Build a few model classes called Posts.java Post.java Image.java
Posts.java
public class Posts {
@SerializedName("posts")
private List<Post> mPosts;
public List<Post> getPosts() {
return mPosts;
}
}
Post.java
public class Post {
@SerializedName("image")
private Image mImage;
public Image getImage() {
return mImage;
}
@SerializedName("caption")
public String mCaption;
public String getCaption() {
return mCaption;
}
}
Image.java
public class Image {
@SerializedName("small")
private String mSmallImageUrl;
public Image getSmallImageUrl() {
return mSmallimageUrl;
}
@SerializedName("large")
public String mLargeImageUrl;
public String getLargeImageUrl() {
return mLargeImageUrl;
}
}
The SerializedName annotation is from the GSON library which should already be part of the Android Studio library packages which you can implement.
It actually creates POJO objects for you all you have to do is create model classes.
With retrofit the implementation is simple in that you declare a RestAdapter somewhere like so:
public class Client {
public static final String API_URL = ".......";
// Constructor which you can initialize somewhere else.
public Client() {
RestAdapter mAsyncRestAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setClient(new OkClient(new OkHttpClient()))
.build();
}
// Implement Interfaces here somewhere.
}
Then create interfaces for your api endpoints like so, this helps decouple things. Note the GET annotation is from retrofit. Retrofit also allows POST PUT DELETE etc.:
public interface IPosts {
@GET("/posts")
void getPosts(Callback<Posts> callback);
}
Notice that Callback is a retrofit callback and upon a 200 OK status it would grab the Response from the API and convert the JSON into the Posts object with GSON.
You would implement the interface like so:
public void getPosts(Callback<Posts> callback) {
IPosts posts = mAsyncRestAdapter.create(IPosts.class);
posts.getPosts(callback);
}
Somewhere in your app just create the following callback:
Callback<Posts> callback = new Callback<Posts>() {
@Override
public void onSuccess(Posts posts, Response response) {
// Do whatever you want with posts here
List<Post> posts = posts.getPosts(); // Get posts for example
}
@Override
public void onFailure(RetrofitError error) {
// Handle the error
}
};
// Pass this callback to the implementation of the interface to have it actually work
mClient.getPosts(callback);
This is one way in which you can easily access nested JSON objects. Retrofit with GSON is a true pleasure to use. The beauty of this method is that all you have to do is define callbacks, interfaces, and models. From which you can see the code is very minimal and decoupled.