Recently in web development, the use of JSON and AJAX data, need to implement the conversion of the object and JSON string, try a variety of methods and class library, found or gson more useful.
Gson is a Java class library provided by Google for mapping between Java objects and JSON data. You can turn a JSON string into a Java object, or vice versa.
Jar Package: http://code.google.com/p/google-gson/downloads/list;
But Goole sometimes not access, you can use this address: Http://mvnrepository.com/search?q=gson;
For more detailed information, refer to this blog: http://blog.csdn.net/lk_blog/article/details/7685169.
A simple Gson test demo is implemented below:
Package Com.demo.util;import Java.util.arraylist;import Java.util.list;import com.demo.domain.account;import Com.google.gson.*;import Com.google.gson.reflect.typetoken;public class Gsontest {public static void main (string[] args) {Gson Gson =new Gson (); Account Account = new account (), Account.setid (0), Account.setusername ("Bowen"), Account.setpassword ("123"); Account.setemail ("[email protected]"); System.out.println ("Convert Bean to Json String ..."); String StrJson1 = Gson.tojson (account); System.out.println (StrJson1); System.out.println ("Convert Json String to Bean ..."); Account account0 = Gson.fromjson (StrJson1, Account.class); System.out.println ("account:" +account0); Account Account1 = new account (), Account1.setid (1), Account1.setusername ("Bowen"), Account1.setpassword ("123"); Account1.setemail ("[email protected]"); Account Account2 = new account (), Account2.setid (2), Account2.setusername ("Bowen"), Account2.setpassword ("123"); Account2.setemail ("[email protected]"); List<account> List = new Arraylist<account> (); List.add (account0); List.add (account1); List.add (Account2); System.out.println ("Convert Bean list to Json String ..."); String strJson2 = Gson.tojson (list); System.out.println (StrJson2); System.out.println ("Convert Json String to Bean list ..."); list<account> accountlist = Gson.fromjson (StrJson2, New typetoken<list<account>> () {}.getType ()); for (account A:accountlist) {System.out.println (a);}}}
Operation Result:
Convert Bean to Json String ... {"id": 0, "username": "Bowen", "password": "123", "Email": "[email protected]"} Convert Json String to Bean ... Account:[email protected]convert Bean list to Json String ... [{"id": 0, "username": "Bowen", "password": "123", "Email": "[email protected]"},{"id": 1, "username": "Bowen", "password" : "123", "Email": "[email protected]"},{"id": 2, "username": "Bowen", "password": "123", "Email": "[email protected]"}] Convert Json String to Bean list ... [Email protected] [Email protected] [Email protected]
Personal lazy, for the realization of the same function, or the easier the better ~
Gson converting JSON strings and Java objects