Retrofit and Json parser

Overview

Retrofit is powerful library that turns your HTTP API into a Java interface. It is very common library. Moreover it can be used to parse Json object to Java object easily. I will suggest my solution for this issue.

How to implement

  1. Intergrade Retrofit library
  2. compile 'com.squareup.retrofit2:retrofit:2.1.0'
    
  3. Create network file
  4. public interface BookService {
        String TAG = BookService.class.getSimpleName();
    
        class Factory {
            public static BookService create() {
                Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://webtruyen.com/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
                return retrofit.create(BookService.class);
            }
        }
    
        @GET("API_IOS/all")
        Observable<Page> getPage(@Query("cate") String cate,
                                 @Query("page") int page,
                                 @Query("perpage") int perPage);
    }
    

    You @Query to add param to api. Moreover you can use @Field, …

  5. Use annotation @SerializedName
  6. public class Page implements Serializable {
        private static final String TAG = Page.class.getSimpleName();
    
        @SerializedName("story")
        private List<Book> bookList;
        @SerializedName("success")
        private int success;
        @SerializedName("numrow")
        private long rowNumber;
    
        public List<Book> getBookList() {
            return bookList;
        }
    
        public void setBookList(List<Book> bookList) {
            this.bookList = bookList;
        }
    
        public int getSuccess() {
            return success;
        }
    
        public void setSuccess(int success) {
            this.success = success;
        }
    
        public long getRowNumber() {
            return rowNumber;
        }
    
        public void setRowNumber(long rowNumber) {
            this.rowNumber = rowNumber;
        }
    }
    

    Using @SerializedName(“numrow”) to show name of attribute on Json object.

In sumary

Retrofit is very useful library. You can research about this library in this link: http://square.github.io/retrofit/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s