Android GSON


Android Google Gson Examples and Tutorials.

Gson (also known as Google Gson) is a small Java-based library for parsing and creating JSON objects.

It's a serialization/deserialization library to convert Java Objects into JSON and back.

Google developed Gson for its own projects, but later made Gson publicly available, starting with version 1.0.

Gson is very powerful and is capable of working with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Uses of Gson

  1. Conversion of Java Objects into JSON and back.
  2. Conversion of a JSON string to an equivalent Java object.

Why Gson was Created

Here are reasons for creation of Gson:

  1. To make working with JSON easy by providing simple toJson() and fromJson() methods. These methods allow us convert Java objects to JSON and vice-versa.
  2. To allow pre-existing unmodifiable objects to be converted to and from JSON.
  3. To provide Extensive support of Java Generics.
  4. To allow custom representations for objects
  5. To provide support for arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Installation of Gson

Gson targets Java based projects including android. That means we have at leats several ways of installing it depending on our build system.

(a) Gradle

For example if you are using android then most likely you are using android studio and gradle.

In that case you add the following in you app level build.gradle's dependencies:

implementation 'com.google.code.gson:gson:2.8.5'

(b) Maven

If you are creating a general java project then most likely you will use Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
</dependency>

(c) Jar

The last option it to use jar directly. You download them from Maven Central and add to your project.

Download Jar here.

Important Classes

(a) Gson

Gson is a class found in com.google.gson package and is the main class we need to use Gson Library.

Normally we use it first by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.

(b). JsonElement

JsonElement is a class found in com.google.gson package that represents an element of Json.

Here are JsonElement Objects:

  1. JsonObject
  2. JsonArray
  3. JsonPrimitive
  4. JsonNull.
(c) JsonObject

JsonObject is a class found in com.google.gson package that represents an object type in Json.

This object can comprise name-value pairs where names are strings, and values are any other type of JsonElement.

With this then we can build a tree of JsonElements. Those elements are maintained in order they were added.

(d) JsonParser

JsonParser is a class found in com.google.gson package that is used to parse Json into a parse tree of JsonElements

Creating Gson

1. Gson()

The first way of creating or constructing Gson object is to use the defalu constructor: Gson().

This will construct us a Gson object with default configuration.

That default configuration has the following settings:

  1. The JSON generated by toJson methods is in compact representation. This means that all the unneeded white-space is removed. You can change this behavior with GsonBuilder#setPrettyPrinting().
  2. The generated JSON omits all the fields that are null. Note that nulls in arrays are kept as is since an array is an ordered list. Moreover, if a field is not null, but its generated JSON is empty, the field is kept. You can configure Gson to serialize null values by setting GsonBuilder#serializeNulls().
  3. Gson provides default serialization and deserialization for Enums, Map, java.net.URL, java.net.URI, java.util.Locale, java.util.Date, java.math.BigDecimal, and java.math.BigInteger classes.
2. GsonBuilder

GsonBuilder can be used to instantiate Gson with various configuration settings.

Gson gson = new GsonBuilder().setPrettyPrinting().create();

GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally calling the create() method.

Important Gson methods

(a). toJson()

This method serializes the specified object, including those of generic types, into its equivalent Json representation.

Gson gson = new Gson();
gson.toJson(map);

It must be used if the specified object is a generic type. For non-generic objects, use toJson(Object,Appendable) instead.

(b). fromJson

This method deserializes the specified Json into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, use fromJson(String,Class) instead.

If you have the Json in a Reader instead of a String, use fromJson(Reader,Type) instead.

(c). toJsonTree

This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements. This method must be used if the specified object is a generic type. For non-generic objects, use toJsonTree(Object)instead.

(d). getAdapter

Returns the type adapter for type.

Full Gson Hello World Example

Let's see a full Gson hello world example. You can copy paste this example into your IDE as long as you have Gson installed and run.

import com.google.gson.Gson;

/** 
 *  Gson Hello World 
 * 
  */ 
public class GsonHelloWorld { 

    public static void main(String[] args) {
        // init class 
        Place place = new Place();
        place.setName("World");

        Human human = new Human();
        human.setMessage("Hi");
        human.setPlace(place);

        // convert to json 
        Gson gson = new Gson();
        String jsonString = gson.toJson(human);
        System.out.println("json " + jsonString); // print "json {"message":"Hi","place":{"name":"World"}}"

        // convert from json 
        Human newHuman = gson.fromJson(jsonString, Human.class);
        newHuman.say(); // print "Hi , World!"
    } 

    private static class Human { 
        private String message;
        private Place place;

        public String getMessage() {
            return message;
        } 

        public void setMessage(String message) {
            this.message = message;
        } 

        public Place getPlace() { 
            return place;
        } 

        public void setPlace(Place place) {
            this.place = place;
        } 

        public void say() { 
            System.out.println();
            System.out.println(getMessage() + " , " + getPlace().getName() + "!");
        } 
    } 

    private static class Place { 
        private String name;

        public String getName() {
            return name;
        } 

        public void setName(String name) {
            this.name = name;
        } 
    } 
} 

Quick GSON Examples and How To's

In these examples we are using Google Gson.

1. How to Convert Map to JSON

Suppose I give you a map with a String key and a T value. And I tell you to map it or convert to a JSON string.

How would you do it?

Well you can simply use the toJson() method of Gson class. You first have to instantiate that Gson class then invoke that method.

    public static <T> String mapToJsonStr(Map<String, T> map) {
        Gson gson = new Gson();
        return gson.toJson(map);
    }
2. How to Convert JSON to Map

What about if you have JSON String and we ask you to convert it to a Map data structure in java.

Well then you would use Gson's fromJson() method.

However this time you must instantiate a TypeToken with that Map as a generic parameter. Then pass the json string as our first parameter in the fromJson() method. And the Type instance as our second parameter.

    public static <T> Map<String, T> jsonStrToMap(String jsonStr) {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, T>>() {
        }.getType();
        return gson.fromJson(jsonStr, type);
    }
3. How to Convert JSON to Object

All right you have a JSON String and you are told to convert it to an Object of given type.

Well, again you pass the json string and the type to the fromJson() method.

    public static <T> T jsonToObj(String jsonStr, Class<T> classOfT) {
        return new Gson().fromJson(jsonStr, classOfT);
    }
4. How to Convert JSON to ArrayList

A common scenario in many projects is to convert a json string to an ArrayList, the most commonly used collection.

We start by using the TextUtils' isEmpty() method to check for empty values.

Then we obtain our TypeToken instance with ArrayList of JSONObjects passed as our generic type.

Then use the fromJson() method to get our ArrayList of JSONObjects.

Then now we can loop through it and to fill the ArrayList that we want to populate.

    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }
5. How to Convert List to JSON

Another common thing is to convert a List to a json string. Maybe you want to serialize that list and send it over the where or a basic way of exposing it as an API.

Again, the toJson() method easily does that for us.

    public static <T> String listToJson(List<T> list) {

        Gson gson = new Gson();
        String jsonstring = gson.toJson(list);
        return jsonstring;

    }
6. How to Convert Object to JSON

You have an object and you should convert it to JSON, well you simply invoke the toJson() method with the object passed as a parameter.

    public static <T> String object2Json(T t) {
        Gson gson = new Gson();
        return gson.toJson(t);
    }
7. How to exclude specific fields from Serialization without annotations

Normally you control fields to include via annotations in Gson. However, can we do it without annotations.

Gson gson = new GsonBuilder()
   .setExclusionStrategies(new TestExclStrat())
   //.serializeNulls() <-- uncomment to serialize NULL fields as well
   .create();
 Student src = new Student();
 String json = gson.toJson(src);
 System.out.println(json);

Reference

8. How to Pretty Print with Gson

PrettyPrinting means adding white-space to make our JSON data more readable. You can use GsonBuilder#setPrettyPrinting().

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);

Reference

9. How to write JSON using TreeModel

Here's the important method. We have two methods for reading and writing json data.

Here's the full class:


import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;

public class TreeModel { 
    public static void main(String[] args) throws IOException {
        System.out.print("readJson: ");
        readJson(); 
        System.out.println();
        System.out.print("writeJson: ");
        writeJson(); 
    } 

    /** 
     *  Example to readJson using TreeModel 
     */ 
    private static void readJson() throws IOException {
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}");
        JsonObject rootObject = jsonElement.getAsJsonObject();
        String message = rootObject.get("message").getAsString(); // get property "message"
        JsonObject childObject = rootObject.getAsJsonObject("place"); // get place object
        String place = childObject.get("name").getAsString(); // get property "name"
        System.out.println(message + " " + place); // print "Hi World!"*/
    } 

    /** 
     * Example to writeJson using TreeModel 
     */ 
    private static void writeJson() throws IOException {
        JsonObject rootObject = new JsonObject();
        rootObject.addProperty("message", "Hi");
        JsonObject childObject = new JsonObject();
        childObject.addProperty("name", "World!");
        rootObject.add("place", childObject);

        Gson gson = new Gson();
        String json = gson.toJson(rootObject);
        System.out.println(json); // print "{"message":"Hi","place":{"name":"World!"}}"
    } 
} 
10. How to Convert String to Object
Gson myGson = new GsonBuilder().setPrettyPrinting().create();
myGson.fromJson(jsonString, Person.class)
11. Pretty Printing JSON String
private static String pretty(String json) {
  JsonElement gson = new JsonParser().parse(json);
  return new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(gson);
 }
}
12. Streaming API Read and Write using Gson

This is an example of JSON Streaming API reading and writing. We will use JsonReader, JsonToken and JsonWriter classes.

We have three methods, our main() method, a readJSON() method and writeJson() method.

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.*; 
import java.nio.charset.Charset;

public class StreamingAPI { 
    public static void main(String[] args) throws IOException {
        System.out.print("readJson: ");
        readJson(); 
        System.out.println();
        System.out.print("writeJson: ");
        writeJson(); 
    } 

    /** 
     *  Example to readJson using StreamingAPI 
     */ 
    private static void readJson() throws IOException {
        String str = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}";
        InputStream in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        while (reader.hasNext()) {
            JsonToken jsonToken = reader.peek();
            if(jsonToken == JsonToken.BEGIN_OBJECT) {
                reader.beginObject();
            } else if(jsonToken == JsonToken.END_OBJECT) {
                reader.endObject();
            } if(jsonToken == JsonToken.STRING) {
                System.out.print(reader.nextString() + " "); // print Hi World!
            } else { 
                reader.skipValue();
            } 
        } 
        reader.close();
    } 

    /** 
     * Example to writeJson using StreamingAPI 
     */ 
    private static void writeJson() throws IOException {
        OutputStream outputStream = new ByteArrayOutputStream();
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.beginObject(); // main object
        writer.name("message");
        writer.value("Hi");
        writer.name("place"); // save object Place
        writer.beginObject();
        writer.name("name");
        writer.value("World!");
        writer.endObject();
        writer.endObject();
        writer.close();
        System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}"
    } 
} 
13. Full Reusable Gson Utility class
ublic class GsonUtils {      

    privatestaticfinaldoubleVERSION=1.0f;      
    private static final Gson sGson = createGson(true, false);

    private static final Gson sGsonExpose = createGson(true, true);

    private GsonUtils () {     
        thrownewAssertionError();  
    } 

    /** 
     * Create the standard {@link Gson} configuration 
     * 
     * @return created gson, never null 
     */ 
    public static Gson createGson() {
        return createGson(true, false); 
    } 

    /** 
     * Create the standard {@link Gson} configuration 
     * 
     * @param serializeNulls whether nulls should be serialized 
     * @return created gson, never null 
     */ 
    private static Gson createGson(final boolean serializeNulls,
                                   final boolean exposeEnable ) {   
        final GsonBuilder builder = new GsonBuilder ();     
        if (serializeNulls) {
            builder.serializeNulls();
        } 
        builder . setVersion ( VERSION );
        // json format 
        // builder.setPrettyPrinting(); 
        if (exposeEnable) {
            builder.excludeFieldsWithoutExposeAnnotation();
        } 
        return builder.create();
    } 

    /** 
     * Get reusable pre-configured {@link Gson} instance 
     * 
     * @return Gson instance 
     */ 
    public static Gson getGson() {
        return sGson;
    } 

    /** 
     * Get reusable pre-configured {@link Gson} instance 
     * 
     * @return Gson instance 
     */ 
    public static Gson getGson(final boolean exposeEnable) {
        return exposeEnable ? sGsonExpose : sGson;
    } 

    /** 
     * Convert object to json, only exports attributes that have been annotated with @Expose 
     * 
     * @param object 
     * @return json string 
     */ 
    public static String toJson(final Object object) {
        return toJson(object, true);
    } 

    /** 
     * Convert object to json 
     * 
     * @param object 
     * @param exposeEnable Whether to export only @Expose annotated properties, true is only exported by @Expose 
     * @return json string 
     */ 
    public static String toJson(final Object object,
                                final boolean exposeEnable ) {   
        return exposeEnable ? sGsonExpose.toJson(object) : sGson.toJson(object);
    } 

    /** 
     * Convert string to given type 
     * 
     * @param json 
     * @param type 
     * @return instance of type 
     */ 
    public static <V> V fromJson(String json, Class<V> type) {
        return sGson.fromJson(json, type);
    } 

    /** 
     * Convert string to given type 
     * 
     * @param json 
     * @param type 
     * @return instance of type 
     */ 
    public static <V> V fromJson(String json, Type type) {
        returnsGson.fromJson(json,type);  
    } 

    /** 
     * Convert content of reader to given type 
     * 
     * @param reader 
     * @param type 
     * @return instance of type 
     */ 
    public static <V> V fromJson(Reader reader, Class<V> type) {
        return sGson.fromJson(reader, type);
    } 

    /** 
     * Convert content of reader to given type 
     * 
     * @param reader 
     * @param type 
     * @return instance of type 
     */ 
    public static <V> V fromJson(Reader reader, Type type) {
        returnsGson.fromJson(reader,type);  
    } 

    /** 
     * Convert object object to map only supports basic types 
     * 
     * @param src 
     * @param exposeEnable 
     * @return 
     */ 
    public static HashMap<String, String> toMap(Object src, boolean exposeEnable) {
        Gson gson = exposeEnable ? sGsonExpose : sGson;
        HashMap<String, String> params = new HashMap<String, String>();
        try { 
            if (src == null) {
                return null; 
            } 
            JsonElement jsonTree = gson . toJsonTree ( src );   
            JsonObject jsonObj = jsonTree.getAsJsonObject();
            Iterator<Entry<String, JsonElement>> iterator = jsonObj.entrySet().iterator();
            String curKey;
            JsonElement curVal ; 
            while (iterator.hasNext()) {
                Entry<String, JsonElement> entry = iterator.next();
                curKey = entry.getKey();
                curVal = entry.getValue();
                if (!curVal.isJsonNull()) {
                    params.put(curKey, curVal.getAsString());
                } 
            } 
            return params;
        } Catch ( Exception e ) {    
            e . printStackTrace ();
        } 
        returnparams; 
    } 

    public static <T> String mapToJson(Map<String, T> map) {
        Gson gson =  new  Gson ();
        return gson . toJson (folder);
    } 
} 

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post