GSONUtils | Gson Singleton Class use Android Tutorial

To Json Parsing We have lot of third party libraries out of these
1:Jackson
2: Gson 2.4



Are using frequently these days but jackson only use where we have more complex data you can say little big data then we should use Jackson otherwise Gson is best to Use .

Step 1:  Make Singleton Class of Gson class like below.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonUtils {
    private static GsonUtils sInstance;
    private Gson mGson;

    private GsonUtils() {
        // mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()           //  .enableComplexMapKeySerialization()           //  .create();           mGson = new Gson();
    }

    public static GsonUtils getInstance() {
        if (sInstance == null) {
            sInstance = new GsonUtils();
        }
        return sInstance;
    }

    public String toJson(Object object) {
        return mGson.toJson(object);
    }

    public Gson getGson() {
        return mGson;
    }
}  


Now You Can use it very easily like this if we have JSON formated data like below example
{
  "type":"object",
  "properties": {
    "foo": {
      "type": "string"
    }
   
  }

}

Call it String rawString;


To parse this we need to make 2 class like this


-----------------------------------
Foo.java and Properties.java--------------

You can also generate these class from jasonschematojava you check this here 10 ShortCuts to make your android development easy and fast


public class Properties {
    @SerializedName("foo")
    @Expose
    private Foo foo;
}  
 -----------------
public class Foo {
    @SerializedName("type")
    @Expose
    private String type;
    /**     *     * @return     * The type       */    public String getType() {
        return type;
    }
    /**     *     * @param type     * The type       */    public void setType(String type) {
        this.type = type;
    }
}  

Now Just Write Down
Properties mProperties=GsonUtils.getInstance().getGson().fromJson(rawString, Properties.class);

Or if you need string from Class then.

rawString =GsonUtils.getInstance(). toJson(mProperties);

Please feel free to comment and share this post.






Previous
Next Post »