Parsing JSON String Into Java Objects


GSON Api consists a Class named Gson in the package 'com.google.gson' which contains a method named fromJson() with that method we can parse Json String to Java Object.

fromJson() method is available with various signatures lets view those

                  <T>T  fromJson(String json, Type typeOfT) 
                  <T>T  fromJson(String json, Class<T> classOfT) 
                  <T>T  fromJson(Reader json, Type typeOfT) 
                  <T>T  fromJson(Reader json, Class<T> classOfT) 
                  <T>T  fromJson(JsonReader reader, Type typeOfT) 
                  <T>T  fromJson(JsonElement json, Type typeOfT) 
                  <T>T  fromJson(JsonElement json, Class<T> classOfT) 
               

To explain the concept I am taking a class named Player with the following structure and I will use this for most of the examples.

/**
 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;

import java.util.LinkedList;
import java.util.List;

public class Player {
  public String name;
  public String gender;
  public int age;
  public List<String> gamesplayed = new LinkedList<>();
}

Now I want to parse this Json String into Java Player's Object using Gson.

/**
 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;
import com.google.gson.Gson;
public class GsonJsonParsingExample {
  public static void main(String args[]) {
    Player obj = null;
    Gson gson = new Gson();
    String json = "{\"name\":\"Alex\",\"gender\":\"Male\",\"age\":25}";
    obj = gson.fromJson(json, Player.class);
    System.out.println("obj.name:" + obj.name + "\tobj.gender:"
        + obj.gender + "\tobj.age" + obj.age);
  }
}

In the above example String json = "{\"name\":\"Alex\",\"gender\":\"Male\",\"age\":25}"; is a JSON string to parse, using gson object's fromJson() method we are doing. as obj = gson.fromJson(json, Player.class);

>_What Will Happen If JSON String doesn't have fileds of JAVA Object?

Gson doesn't throw any exception if the JSON string doesn't have the fileds of Java Object which passed for parsing. Simply parse and convert the matched fields to Java Object.

Check this JSON String which doesn't have the name,age fields even the Gson convertion doesn't through the errors.

check this example and output.

/**
 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;
import com.google.gson.Gson;
public class GsonJsonParsingExample {
  public static void main(String args[]) {
    Player obj = null;
    Gson gson = new Gson();
    String json = "{\"na\":\"Alex\",\"gender\":\"Male\"}";
    obj = gson.fromJson(json, Player.class);
    System.out.println("obj.name:" + obj.name + "\tobj.gender:"
        + obj.gender + "\tobj.age:" + obj.age);
  }
}
Output:-
obj.name:null obj.gender:Male obj.age: 0

>_When we will get the Exception while using fromJson()

  1. > All fromJson() methods will throws JsonSyntaxException
  2. > JsonSyntaxException will be fired if the 'Malformed Json String supplied' or 'Invalid data type present while parsing'

For the above example 'age' field is of integer type. If I supplied non-integer value for age field then fromJson() method will fire JsonSyntaxException with the cause 'NumberFormatException'.

Check this example

/**
 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;
import com.google.gson.Gson;
public class GsonJsonParsingExample {
  public static void main(String args[]) {
    Player obj = null;
    Gson gson = new Gson();
    String json = "{\"age\":2.5}";
    obj = gson.fromJson(json, Player.class);
    System.out.println("obj.name:" + obj.name + "\tobj.gender:"
        + obj.gender + "\tobj.age" + obj.age);
  }
}
Output:-
Exception in thread "main" com.google.gson.JsonSyntaxException: 
java.lang.NumberFormatException: Expected an int but was 2.5 at line 1 column 11
  at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:232)
  at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:222)
Copyright © 2018-2020 TutorialToUs. All rights reserved.