Let’s say that we need to consume JSON objects and load them as Java objects. Assume that a web server will produce the following JSON when queried:
{ NAME:"SAHIL", LANGUAGE:"Java", LOCATION:"Gurgaon" }
This JSON object contains three fields with their respective values. Let’s say that we need to consume the JSON object and create a Java object that represents this data. To make this example more interesting, let assume that we’re only interested in the name and the location fields.
First we need to create a Java class with the fields that we want to represent (name and location). Let’s call the class Person. The name of this class is irrelevant, but the names of the fields are not. The field names must match (including the case) with the names in JSON. Furthermore, the class must include a default constructor (even in this is set as private). As shown below, the fields name and location are in uppercase as found in JSON. The JSON field P_LANGUAGE is ignored as the Java object does not include a field with this name. It is understandable that the fields’ names do not follow the Java naming convention, but for the time being let’s keep things simple.
public class Person {
private String NAME;
private String LOCATION;
**// Getters and setters are not required for this example.
// GSON sets the fields directly using reflection.**
@Override
public String toString() {
return NAME + " - " + LOCATION;
}
}
With the Java object ready, we can read the JSON objects and load them as Java objects as illustrated below. To simulate a real life situation, we’re using a byte stream as input. Also note that the JSON content is saved into a file (which is not usually the case) located in the resources source folder.
public class JsonToJava {
public static void main(String[] args) throws IOException {
try(Reader reader = new InputStreamReader(JsonToJava.class.getResourceAsStream("/Server1.json"), "UTF-8")){
Gson gson = new GsonBuilder().create();
Person p = gson.fromJson(reader, Person.class);
System.out.println(p);
}
}
}
This should produce the following:
SAHIL - Gurgaon
Gson parsed the JSON object and created an instance of the Person class which is then printed to the command prompt.
Hope this will clear your doubt , please comment in case some doubt is still there , will clear it .
Thanx in Advance .