Google Gson Usage Profile

Source: Internet
Author: User
Tags string back tojson

Reprint: http://www.cnblogs.com/haippy/archive/2012/05/20/2509329.html

In the following example, we have an example of how to convert a data to a JSON string and use a  Gson.toJson() method to serialize the array to JSON, and the method to deserialize the Gson.fromJson() JSON string into a Java array.

Import Com.google.gson.gson;public class Arraytojson {public static void main (string[] args) {int[] numbers =        {1, 1, 2, 3, 5, 8, 13};        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};        Create a new instance of Gson//Gson Gson = new Gson ();        Convert numbers array into JSON string.        String Numbersjson = Gson.tojson (numbers);        Convert strings array into JSON string//String Daysjson = Gson.tojson (days);        System.out.println ("Numbersjson =" + Numbersjson);        System.out.println ("Daysjson =" + Daysjson);        Convert from JSON string to a primitive array of int.        int[] Fibonacci = Gson.fromjson (Numbersjson, Int[].class);        for (int i = 0; i < fibonacci.length; i++) {System.out.print (Fibonacci[i] + "");        } System.out.println (""); Convert from JSON string to aString array.        string[] weekdays = Gson.fromjson (Daysjson, String[].class);        for (int i = 0; i < weekdays.length; i++) {System.out.print (Weekdays[i] + "");        } System.out.println (""); Converting multidimensional array into JSON//int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}}        ;        String JSON = Gson.tojson (data);        System.out.println ("Data =" + json);        Convert JSON string into multidimensional array of int.        int[][] DataMap = Gson.fromjson (JSON, int[][].class); for (int i = 0, i < data.length; i++) {for (int j = 0; J < Data[i].length; J + +) {System.            Out.print (Data[i][j] + "");        } System.out.println (""); }    }}

The following are the output results:

Numbersjson = [1,1,2,3,5,8,13]daysjson = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]1 1 2 3 5 8 Sun Mon Tue Wed Thu Fri Sat Data = [[1,2,3],[3,4,5],[4,5,6]]1 2 3 3 4 5

How do I convert a collection to a JSON string?

In the following example, we have an example of how to convert a Java collection into a string that conforms to a JSON rule.

Import Java.util.date;public class Student {    private String name;    Private String address;    Private Date dateOfBirth;    Public Student () {    } public    Student (string name, string address, Date dateOfBirth) {        this.name = name;        this.address = address;        This.dateofbirth = dateOfBirth;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public String getaddress () {        return address;    }    public void setaddress (String address) {        this.address = address;    }    Public Date Getdateofbirth () {        return dateofbirth;    }    public void Setdateofbirth (Date dateofbirth) {        This.dateofbirth = dateOfBirth;    }}
Import Com.google.gson.gson;import Com.google.gson.reflect.typetoken;import Java.lang.reflect.type;import Java.util.arraylist;import Java.util.date;import Java.util.list;public class Collectiontojson {public static void main (string[] args)        {////Converts a collection of string object into JSON string.        list<string> names = new arraylist<string> ();        Names.add ("Alice");        Names.add ("Bob");        Names.add ("Carol");        Names.add ("Mallory");        Gson Gson = new Gson ();        String jsonnames = Gson.tojson (names);        System.out.println ("jsonnames =" + jsonnames); Converts a collection Student object into JSON string//Student a = new Student ("Alice", "Appl        E St ", New Date (2000, 10, 1));        Student B = new Student ("Bob", "Banana St", null);        Student C = new Student ("Carol", "Grape St", New Date (2000, 5, 21));        Student d = new Student ("Mallory", "Mango St", null);list<student> students = new arraylist<student> ();        Students.add (a);        Students.add (b);        Students.add (c);        Students.add (d);        Gson = new Gson ();        String jsonstudents = Gson.tojson (students);        System.out.println ("jsonstudents =" + jsonstudents);        Converts JSON string into a collection of Student object.        Type type = new Typetoken<list<student>> () {}.gettype ();        list<student> studentlist = Gson.fromjson (jsonstudents, type);        for (Student student:studentlist) {System.out.println ("student.getname () =" + Student.getname ()); }    }}

The following are the output results:

Jsonnames = ["Alice", "Bob", "Carol", "Mallory"]jsonstudents = [{"Name": "Alice", "Address": "Apple St", "dateOfBirth": " Nov 1, 3900 12:00:00 AM "},{" name ":" Bob "," Address ":" Banana St "},{" name ":" Carol "," Address ":" Grape St "," dateOfBirth ":" June, 3900 12:00:00 AM "},{" name ":" Mallory "," Address ":" Mango St "}]student.getname () = alicestudent.getname () = Bobstudent.getname () = carolstudent.getname () = Mallory

How do I convert a map to a JSON string?

In the example below, we will convert the JSON string into a java.util.Map java.util.Map

Import Com.google.gson.gson;import Com.google.gson.reflect.typetoken;import Java.lang.reflect.type;import Java.util.hashmap;import Java.util.map;public class Maptojson {public static void main (string[] args) {map<        String, string> colours = new hashmap<string, string> ();        Colours.put ("BLACK", "#000000");        Colours.put ("RED", "#FF0000");        Colours.put ("GREEN", "#008000");        Colours.put ("BLUE", "#0000FF");        Colours.put ("YELLOW", "#FFFF00");        Colours.put ("White", "#FFFFFF");        Convert a Map into JSON string.        Gson Gson = new Gson ();        String JSON = Gson.tojson (colours);        SYSTEM.OUT.PRINTLN ("JSON =" + JSON);        Convert JSON string back to Map.        Type type = new typetoken<map<string, string>> () {}.gettype ();        map<string, string> map = Gson.fromjson (JSON, type); For (String Key:map.keySet ()) {System.out.println ("map.gET = "+ map.get (key)); }    }}

The following are the output results:

JSON = {"White": "#FFFFFF", "BLUE": "#0000FF", "YELLOW": "#FFFF00", "GREEN": "#008000", "BLACK": "#000000", "RED": "#FF0000 "}map.get = #FFFFFFmap. Get = #0000FFmap. Get = #FFFF00map. Get = #008000map. Get = #000000map. Get = #FF0000

How do I convert an object to a JSON string?

In the example below, we have an example of how to convert a Student object into a JSON string, and in practice we can convert any Java class to a JSON string, and it is very simple to implement, you just need to create an Gson instance, then pass the object that will be converted to JSON string and call The ToJson method of the instance can be used.

Import Com.google.gson.gson;import Java.util.calendar;public class Studenttojson {public    static void main (string[ ] args) {        Calendar dob = Calendar.getinstance ();        Dob.set (1, 1, 0, 0, 0);        Student Student = new Student ("Duke", "Menlo Park", Dob.gettime ());        Gson Gson = new Gson ();        String JSON = Gson.tojson (student);        SYSTEM.OUT.PRINTLN ("JSON =" + JSON);}    }
Import Java.util.date;public class Student {    private String name;    Private String address;    Private Date dateOfBirth;    Public Student () {    } public    Student (string name, string address, Date dateOfBirth) {        this.name = name;        this.address = address;        This.dateofbirth = dateOfBirth;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    Public String getaddress () {        return address;    }    public void setaddress (String address) {        this.address = address;    }    Public Date Getdateofbirth () {        return dateofbirth;    }    public void Setdateofbirth (Date dateofbirth) {        This.dateofbirth = dateOfBirth;    }}

The following are the output results:

JSON = {"name": "Duke", "Address": "Menlo Park", "dateOfBirth": "Feb 1, 12:00:00 AM"}

How do I convert a JSON string to an object?

In the following example, we sample how JSON strings are converted to Java objects.

Import Com.google.gson.gson;public class Jsontostudent {public    static void Main (string[] args) {        String json = "{ \ "name\": \ "duke\", \ "address\": \ "Menlo park\", \ "dateofbirth\": \ "Feb 1," 12:00:00 am\ "}";        Gson Gson = new Gson ();        Student Student = Gson.fromjson (JSON, student.class);        System.out.println ("student.getname ()        =" + Student.getname ());        System.out.println ("student.getaddress ()     =" + student.getaddress ());        System.out.println ("student.getdateofbirth () =" + Student.getdateofbirth ());}    }

The following are the output results:

Student.getname ()        = dukestudent.getaddress ()     = Menlo Parkstudent.getdateofbirth () = Tue Feb 00:00:00 CST 2000

How do I work with the fields of an object?

In the following example, we can use Gson to manipulate a field of an object.

Import Com.google.gson.gson;import Java.util.calendar;public class Gsonfieldexample {public    static void main ( String[] args) {        Calendar dob = Calendar.getinstance ();        Dob.set (1980, ten, one);        People people = New People ("John", "Banana St.", Dob.gettime ());        People.setsecret ("This is a secret!");        Gson Gson = new Gson ();        String json = Gson.tojson (people);        SYSTEM.OUT.PRINTLN ("JSON =" + JSON);}    }
Import Java.util.date;public class People {    private String name;    Private String address;    Private Date dateOfBirth;    Private Integer age;    private transient String secret;    Public people (string name, string address, Date dateOfBirth) {        this.name = name;        this.address = address;        This.dateofbirth = dateOfBirth;    }    Public String Getsecret () {        return secret;    }    public void Setsecret (String secret) {        this.secret = secret;    }}

The following are the output results:

JSON = {"name": "John", "Address": "Banana St.", "dateOfBirth": "Nov One, 1980 8:47:04 AM"}

Google Gson Usage Profile

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.