Leo Leo is a Java Geek and had the opportunity to apply his skills to various industry, from aerospace, e-commerce, and gaming. Leo is a DZone MVB and is not an employee of DZone and has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

JSon GSon

07.12.2011
| 6171 views |
  • submit to reddit

JSON is a wide spread data description format used to exchange JavaScript Objects.
While implementing new functionality for OGL Explorer, I have found that it was pretty widely used by lots of web APIs.

So today, I will focus on the exploitation of this kind of data in Java, with the pretty well done GSon library.
First, call the service (a simple GET with the arguments in the URL) that provide the data, this is done simply by this code :

    public static String call(String url) throws IOException {  
        BufferedReader bis = null;  
        InputStream is = null;  
        try {  
            URLConnection connection = new URL(url).openConnection();  
            is = connection.getInputStream();  
            // warning of UTF-8 data  
            bis = new BufferedReader(new InputStreamReader(is, "UTF-8"));  
            String line = null;  
            StringBuffer result = new StringBuffer();  
            while ((line = bis.readLine()) != null) {  
                result.append(line);  
            }  
            return result.toString();  
        } finally {  
            if (bis != null) {  
                try {  
                    bis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (is != null) {  
                try {  
                    is.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  

Note : we use a InputStreamReader(is, “UTF-8″) in order to manage correctly UTF-8 data that we’ll retrieve in some Japanese, French or other exotic languages.

Ok, the String result will be the something, for example like that :

{
     "first-name": "John",
     "last-name": "Smith",
     "age": 25,
     "address":
     {
         "street-address": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postal-code": "10021"
     },
     "phone-number":
     [
         {
           "type": "home",
           "number": "212 555-1234"
         },
         {
           "type": "fax",
           "number": "646 555-4567"
         }
     ]
 }

To process this String, we’ll use the magic GSon.

The GSon library will try to parse the JSon formatted string and map the data to a given Java Person Object. GSon used reflection to do such a trick, so the attributes types and names of the target java Object will need to be matchable with the JSon string structure.
In the previous example, the Person object will need to have a structure that match the JSon object, that is to say, will have 5 attributes named “first-name”, “last-name”, “age”, “address”, and “phone-number”.

First of all, what we see here, is that an attribute cannot be called first-name in Java, because the ‘-’ character is not permitted in java attribute names. No problem, we’ll declare a firstName attribute, and specify that it’s JSon serialized name id “first-name” by using a @SerializedName annotation.

We’ll obtain an attribute declared like this :

@SerializedName("first-name") private String firstName; 

Of course same trick is applied for the “last-name” attribute.
The age is simply declared as a int, here we keep the same attribute name in JavaScript and in Java :

    private int age;  

Ok, now the address, which is a complex Object (we can see it with the {…} that represents a structure.
So we’ll map it with a Java Object Address, which following the same principle as above, which give us :

private class Address {  
    @SerializedName("street-address") private String streetAddress;  
    private String city;  
    private String state;  
    @SerializedName("postal-code") private int postalCode;  
}

Remain the phone numbers, here the [...] characters point out that we are dealing with a collections of objects.
We’ll then map it with a java.util.List of PhoneNumber Objects as below :

    @SerializedName("phone-number") private List<PhoneNumber> phoneNumber;  

Where a PhoneNumber is the given object :

    private class PhoneNumber {  
        private String type;  
        private String number;  
    }  

OK, so now our Object Person is completed and looks like that :

    private class Person {  
        @SerializedName("first-name") private String firstName;  
        @SerializedName("last-name") private String lastName;  
        private int age;  
        private Address address;  
        @SerializedName("phone-number") private List<PhoneNumber> phoneNumber;  
    }  

We are done. A call to Gson will instantiate a Person Java Object and populate it with the flux.

    Person data = new Gson().fromJson(json, Person .class);  

That give us :
json

 

From http://lewisleo.blogspot.jp/2012/08/json-gson.html

Published at DZone with permission of Leo Lewis, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Juan Macias replied on Wed, 2011/07/13 - 5:44am

Pretty cool, thanks for sharing!

Marc Stock replied on Tue, 2011/07/19 - 11:35am

Does the performance of gson still suck? Do some comparisons between it and Jackson and you'll get an idea what I'm talking about.

Leo Lewis replied on Wed, 2011/07/20 - 1:36am in response to: Marc Stock

Marc,

Indeed, I have done some very simplistic benchmark on reading/writing data,something like executing nbLoops times :

Person person = gson.fromJson(json, Person.class);
String result = gson.toJson(person); 

or 

Person person = jackson.readValue(json, Person.class);
String result = jackson.writeValueAsString(person); 

On my computer, when nbLoops is lower than 70, Gson is better, otherwise Jackson is better.

It seems to confirm what is said on different sources such as :

http://stackoverflow.com/questions/2378402/jackson-vs-gson

http://www.martinadamek.com/2011/02/04/json-parsers-performance-on-android-with-warmup-and-multiple-iterations/

http://stackoverflow.com/questions/338586/a-better-java-json-library

 

Personally, in my use of GSon, I didn't need incredible performances. Also the javascript object parsed from the flux was not the Java object that I used in fine in my application. For this reason, what I like about GSon is that you don't need to have Java Bean objects to be able to parse them. Which make code more simple/compact, especially when if it's just some private temporary object.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.