Gson Framework Instances

Source: Internet
Author: User
Tags tojson

 PackageCom.json;Importjava.util.ArrayList;Importjava.util.Date;ImportJava.util.HashMap;ImportJava.util.LinkedHashMap;Importjava.util.List;ImportJava.util.Map;ImportCom.google.gson.FieldNamingPolicy;ImportCom.google.gson.Gson;ImportCom.google.gson.GsonBuilder;ImportCom.google.gson.reflect.TypeToken;/*** This article refers to:http://blog.csdn.net/lk_blog/article/details/7685190 * */ Public classJsondemo {PrivateList<person>personlist; PrivatePerson Persondemo; PrivateGson Gson;  Public voidInitpersondata () {Persondemo=NewPerson ("I am Demo", 40, "China",NewDate ()); Person P1=NewPerson ("Zhang San", 20, "Beijing",NewDate ()); Person P2=NewPerson ("John Doe", 22, "Shanghai",NewDate ()); Person P3=NewPerson ("Harry", 30, "Guangzhou",NewDate ()); Personlist=NewArraylist<person>();        Personlist.add (Persondemo);        Personlist.add (p1);        Personlist.add (p2);    Personlist.add (p3); }     Public Static voidMain (string[] args) {Jsondemo demo=NewJsondemo (); intTesttype = 5; Switch(testtype) { Case1://Simple Object conversions and list conversions with genericsDemo.initpersondata (); Demo.gson=NewGson ();            Demo.printpersonresult ();  Break;  Case2://Gson Annotations and GsonbuilderDemo.initpersondata (); //Note that the Gson is constructed in Gsonbuilder, which differs from the Gson Gson = new Gson () in test1;Demo.gson =NewGsonbuilder (). Excludefieldswithoutexposeannotation ()//do not export attributes with @expose annotations in the entity. Enablecomplexmapkeyserialization ()//Map-enabled key is the form of a complex object. Serializenulls (). Setdateformat ("Yyyy-mm-dd HH:mm:ss:SSS")//time into a specific format. Setfieldnamingpolicy (Fieldnamingpolicy.upper_camel_case)//The first letter of the field is capitalized, note: The @serializedname annotation used on the entity will not take effect.. Setprettyprinting ()//formats the JSON result.. Setversion (1.0)//Some fields are not initially available and will be added as the version is upgraded, so the serialization and serialization are selected for serialization based on the version number. //the @Since (version number) is perfect for this function. Also the fields may be deleted as the version is upgraded, then//@Until (version number) can also implement this function, the gsonbuilder.setversion (double) method needs to be called.. Create ();            Demo.printpersonresult ();  Break;  Case3://example of Gson-map processingDemo.testmap1 ();  Break;  Case4://Map Processingdemo.testmap2 ();  Break;  Case5://Map Processingdemo.testmap3 ();  Break; }    }     Public voidTestMap1 () {Map<point, string> map1 =NewLinkedhashmap<point, string> ();//use Linkedhashmap to arrange results in FIFO orderMap1.put (NewPoint (3, 6), "P1"); Map1.put (NewPoint (4, 8), "P2"); Gson=NewGsonbuilder (). Enablecomplexmapkeyserialization (). Create (); String Str=Gson.tojson (MAP1); System.out.println (str);//results: [[{"X": 3, "Y": 6}, "P1"],[{"x": 4, "Y": 8}, "P2"]]Map<point, string> retmap = Gson.fromjson (str,NewTypetoken<map<point, string>>() {}.gettype ());  for(Point P:retmap.keyset ()) {System.out.println ("Key:" + P + ", Values:" +Retmap.get (p));    } System.out.println (Retmap); }     Public voidtestMap2 () {Map<string, point> map1 =NewLinkedhashmap<string, point> ();//use Linkedhashmap to arrange results in FIFO orderMap1.put ("a",NewPoint (3, 6)); Map1.put ("B",NewPoint (4, 8)); Gson=NewGsonbuilder (). Enablecomplexmapkeyserialization (). Create (); String Str=Gson.tojson (MAP1); System.out.println (str);//results: [[{"X": 3, "Y": 6}, "P1"],[{"x": 4, "Y": 8}, "P2"]]Map<string, point> retmap = Gson.fromjson (str,NewTypetoken<map<string, point>>() {}.gettype ());  for(String p:retmap.keyset ()) {System.out.println ("Key:" + P + ", Values:" +Retmap.get (p));    } System.out.println (Retmap); }     Public voidtestMap3 () {initpersondata (); Map<string, object> map =NewHashmap<string, object>(); Map.put ("Persons", personlist); List<Point> pointlist =NewArraylist<point>(); Pointlist.add (NewPoint (3, 6)); Pointlist.add (NewPoint (4, 6)); Pointlist.add (NewPoint (4, 7)); Map.put ("Points", pointlist); Gson=NewGson (); String Str=Gson.tojson (map); System.out.println (str);//Result: {"persons": [{"Name": "I am Demo", "Age": +, "address": "China", "Bir": " the"//1, 1:59:39//PM "},{" name ":" Zhang San "," Age ":" Address ":" Beijing "," Bir ":"//1, 1:59:39//PM "},{" name ":" John Doe "," Age ":" Address ":" Shanghai "," Bir ":"//1, 1:59:39//PM "},{" name ":" Harry "," age ": +," Address ":" Guangzhou "," Bir ":" The "//1, 1:59:39//PM "}]," points ": [{" X ": 3," Y ": 6},{" x ": 4," Y ": 6},{" x ": 4," Y ": 7}]}Map<string, object> retmap =Gson.fromjson (str,NewTypetoken<map<string, list<object>>>() {}.gettype ());  for(String key:retMap.keySet ()) {if("Persons". Equals (Key) {List<Person> pList = (list<person>) Retmap.get (key);            System.out.println (pList); }Else if("Points". Equals (Key) {List<Point> pList = (list<point>) Retmap.get (key);            System.out.println (pList); }        }        }    Private voidPrintpersonresult () {System.out.println ("============ Transformation of Simple Objects =============="); String P1json=Gson.tojson (Persondemo);        System.out.println (P1json); Person Refperson= Gson.fromjson (P1json, person.class);        System.out.println (Refperson); System.out.println (""); System.out.println ("============ with generic list conversion =============="); String Jsonstr=Gson.tojson (personlist); System.out.println ("Jsonstr:" +jsonstr); List<Person> reflist = Gson.fromjson (Jsonstr,NewTypetoken<list<person>>() {}.gettype ());  for(person per:reflist) {System.out.println (per); }    }}

Gson Framework Instances

Related Article

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.