Sunday, December 25, 2011

Serialize an Object to a JSON String in Java Using Gson

To serialize a specified object or bean into its equivalent Json representation in Java we can use Google's GSON library. First create a serializable object and set its fields to some values. Next new up a com.google.gson.Gson object. Finally call the Gson objects's toJson() method passing it your serializable object.


import com.google.gson.Gson;

// The following example code demonstrates how to serialize a Bean
// object to a JSON String using the GSON library from Google.

public class Bean2JsonUsingGson {

    public static void main(String[] args) {

        SampleBean sampleBean = new SampleBean(3.14, "xyz", 42);
        Gson gson = new Gson();
        String json = gson.toJson(sampleBean);

        System.out.println(json);
    }

    static class SampleBean {

        private double value1;
        private String value2;
        private int value3;

        // Constructor
        SampleBean(double value1, String value2, int value3) {
            this.value1 = value1;
            this.value2 = value2;
            this.value3 = value3;
        }
    }
}

Here is the output of the example program:
{"value1":3.14,"value2":"xyz","value3":42}

Piece of cake!!!

No comments: