Android JSON Parser - Custom Library

Android JSON Parser - Custom Library Like you, I am a programmer trying to make a living by developing apps. When it comes to Androi...


Android JSON Parser - Custom Library

Like you, I am a programmer trying to make a living by developing apps. When it comes to Android, I found my life a bit easier because of rich tools like IntelliJ IDEA used as the official Android IDE, well-written documentations, good supports, big community, etc. I could make a blog about good things of Android. But here in this blog, I got a bit of a problem: the problem of libraries.
It made me crazy when finding myself repeating the same things over and over again. How come? I am still asking this question.

Recently, I worked on a project of making an Android app to read JSON data from a web service that stored data in MySQL. In the app, I wanted to read data from tbl_user, tbl_product, tbl_category, tbl_order etc. Basically, you need a class used as a model class to represent a table. Hence, you have four different classes with different attributes. To parse JSON to object, first you call a JSONArray class from org.json package to read a JSON text. Then you need a loop (for loop mostly) to read data from JSON and store it in each attributes of a class. Below is snippet of the codes:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
...
try{
   String jSonText = 
   "[{\"id\":\"1\",\"username\":\"sok\",\"password\":\"123\"}";
   
    JSONArray jArray = new JSONArray(jSonText);
    List<User> userList = new ArrayList<User>();
    for(int i = 0; i < jArray.length() ; i++){
        JSONObject jsObj = jArray.getJSONObject(i);
        User user = new User();
        user.id(Integer.parseInt(jsObj.getString("id")));
        user.username(jsObj.getString("username"));
        user.password(jsObj.getString("password"));
        userList.add(user);
    }//end for

} catch (JSONException e) {
    //error message
}//end try
...
public class User{
    public int id;
    public String username;
    public String password;
}
I have 4 tables so I had to write these same codes 4 times. This block of code repeats over and over again. I told myself there should be a better way. Then I looked for help, yes, on Google. I tried some keywords like "generic json parser arraylist" or "generic json converter arraylist" in Google, I was surprise to see the result which is less than 250,000 (on 2015-09-07). And you will see the top results are coming from StackOverlow. How come there is no link to an official Android library or Google library? So I had to go each questions and all answers in StackOverflow. I found some good answers but not complete. Then I need to work out with the puzzle, and finally I created a good generic class that can convert/parse a JSON text into an ArrayList or List of a generic class.

So are you ready to make your life easier?

REUSABLE JSON CONVERTER TO GENERIC ARRAYLIST

Step 1 - Add GSON Library

This class uses GSON from Google. First you need to download the GSON jar file by visiting this website. Make sure you add it as a library by copying the jar file into libs folder > right clicking on it > choose Add as Library. Or a better way, just add a Gradle as shown below into your dependencies.
compile 'com.google.code.gson:gson:2.2.4'

Step 2 - Create JsonConverter Class

This is the important class. This class consists of one method: ArrayList<T> toArrayList. But because some prefers a return type as List, I created another method List<T> toList. The two methods do exactly the same thing except the return type. What it does is taking a JSON String and using GSON to convert it. However, here we want it to convert to a list of any generic type. That's why you need to supply a Class<T> class as a second argument.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JsonConverter<T> {

    public ArrayList<T> toArrayList(String jsonString, Class<T> clazz){
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat("dd/MM/yy HH:mm:ss");
        Gson gson = builder.create();
        Type type = new ListParameterizedType(clazz);
        ArrayList<T> list = gson.fromJson(jsonString, type);

        return list;
    }

    public List<T> toList(String jsonString, Class<T> clazz) {

        List<T> list = toArrayList(jsonString, clazz);

        return list;
    }

    private static class ListParameterizedType implements ParameterizedType {

        private Type type;

        private ListParameterizedType(Type type) {
            this.type = type;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[] {type};
        }

        @Override
        public Type getRawType() {
            return ArrayList.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }

    }
}

Step 3 - Add @SerializedName

In your model class, you should add @SerializedName on each attributes. See a sample code below:
import com.google.gson.annotations.SerializedName;

public class Product {
    @SerializedName("id")
    public Integer id;
    @SerializedName("username")
    public String username;
    @SerializedName("password")
    public Double password;
}

Step 4 - Usage

To use it, what you have to do is to call toArrayList method and pass in a JSON text and a model class, e.g. User.
String jSonText = 
"[{\"id\":\"1\",\"name\":\"Sao\",\"username\":\"sok\",\"password\":\"123\"}]";

ArrayList<User> userList = 
        new JsonConverter<User>().toArrayList(json, User.class);
That's it. It is just one line of code. If you have another model, you repeat step 3 and step 4. It will save a lot of times and headache.

DOWNLOAD

If you don't want to create the class in step 2 yourself, you can download a Jar file from my GitHub at https://github.com/kosalgeek/KGJsonConverter. However, please note that even though you download my library, you still need to add the GSON library as well. To do that, read step 1.

Written by Oum SaokosalKosalGeek, Top12Review.


Photo Credit:

Samsung Galaxy Note 3 by Sergey Galyonkin / CC BY

COMMENTS

BLOGGER: 1
Loading...
Name

Android Java for Android
false
ltr
item
Android Programming Language Step by Step | KosalGeek: Android JSON Parser - Custom Library
Android JSON Parser - Custom Library
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsyyttfKW9AhfOfAM8x61Tf4ybiieOf4WFrsNEjnI0-VXj_U1dlPUVzYDAacuOWbcPiQbAk8_pCqmklyxhMjcvQYOkeSDiyMNh1RDY7Q1ho34O_y03tWbRH88bkSl6Y7lCXypgGSAUN1U/s320/Android+JSON+Parser.jpg
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsyyttfKW9AhfOfAM8x61Tf4ybiieOf4WFrsNEjnI0-VXj_U1dlPUVzYDAacuOWbcPiQbAk8_pCqmklyxhMjcvQYOkeSDiyMNh1RDY7Q1ho34O_y03tWbRH88bkSl6Y7lCXypgGSAUN1U/s72-c/Android+JSON+Parser.jpg
Android Programming Language Step by Step | KosalGeek
https://kosalgeek.blogspot.com/2015/09/android-json-parser.html
https://kosalgeek.blogspot.com/
http://kosalgeek.blogspot.com/
http://kosalgeek.blogspot.com/2015/09/android-json-parser.html
true
1541123312426289231
UTF-8
Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy