Gson Study Notes

Source: Internet
Author: User
Tags array example tojson
Primitives examples // basic example PS serialization: JavaBean --> JSON format deserialization: JSON format --> JavaBean (serialization) gson = new gson (); gson. tojson (1); ==> prints 1gson. tojson ("ABCD"); ==> prints "ABCD" gson. tojson (New Long (10); ==> prints 10int [] values = {1}; gson. tojson (values); ==> prints [1] (deserialization) int one = gson. fromjson ("1", Int. class); integer one = gson. fromjson ("1", integer. Class); long one = gson. fromjson ("1", long. class); Boolean false = gson. fromjson ("false", Boolean. class); string STR = gson. fromjson ("ABC" ", String. class); string anotherstr = gson. fromjson ("[" ABC "]", String. class); object examples // custom class bagofprimitives {private int value1 = 1; private string value2 = "ABC"; private transient int value3 = 3; bagofprimitives () {// No-ARGs constructor} (seriali Zation) bagofprimitives OBJ = new bagofprimitives (); gson = new gson (); string JSON = gson. tojson (OBJ); ==> JSON is {"value1": 1, "value2 ": "ABC"} // note that the value3 = 3 Java keyword transient does not appear here. If transient is used to declare an instance variable, when the object is stored, its value does not need to maintain gson, so it will not serialize his (deserialization) bagofprimitives obj2 = gson. fromjson (JSON, bagofprimitives. class); finer points with objects // small detail 1. during serialization, an empty field will be skipped and deserialized, And the entries in the corresponding fields of the Set object will lose the JSON result. Null: If a field is manually merged, it will be ignored, not included in the JSON serialization or deserialization of the corresponding internal class, Anonymous class and external class fields are ignored, and does not include in serialization or deserialization Nested classes (including inner classes) // Nested classes (including internal classes) ublic Class A {public string a; Class B {Public String B; public B () {// No ARGs constructor for B }}// this is a member's internal class gson. When serializing A, ba A = new A ();. A = "aaaaaa";. B = new. new B (); B. B = "bbbbbb"; gson G = new gson (); string atext = G. tojson (a); system. out. println (atext); j Son --> "A": "aaaaaa" array examples // array example gson = new gson (); int [] ints = {1, 2, 3, 4, 5}; string [] strings = {"ABC", "def", "Ghi"}; (serialization) gson. tojson (ints); ==> prints [1, 2, 3, 4, 5] gson. tojson (strings); ==> prints ["ABC", "def", "Ghi"] (deserialization) int [] ints2 = gson. fromjson ("[1, 2, 3, 4, 5]", int []. class) ;=> ints2 will be same as ints supports multi-dimensional arrays, any Complex Element type collections examples // set <generic> instance gson GSO N = new gson (); collection <integer> ints = lists. immutablelist (1, 2, 3, 4, 5); (serialization) string JSON = gson. tojson (ints); ==> JSON is [1, 2, 3, 4, 5] (deserialization) // use deserialization if you want to keep the generic type collectiontype = new typetoken <collection <integer> (){}. getType (); collection <integer> ints2 = gson. fromjson (JSON, collectiontype); ints2 is same as intsfairly hideous: note how we define the type of collectionunfortuna Tely, no way to get around this in your erializing and deserializing generic types generic type footype = new typetoken <Foo <bar> (){}. getType (); gson. tojson (Foo, footype); gson. fromjson (JSON, footype) serializing and deserializing collection with objects of arbitrary types any set of image types ['hello', 5, {Name: 'greetings ', source: 'Guest '}] the equivalent collection containing this is: Collection collection = new ARRA Ylist (); Collection. add ("hello"); Collection. add (5); Collection. add (new event ("greetings", "guest"); where the event class is defined as: class event {private string name; private string source; Private event (string name, string source) {This. name = Name; this. source = source ;}{ name: 'greetings ', source: 'guest'} will not be parsed as the event class excluding fields from serialization and deserialization Filter field gson's @ expose Use annotaion annotation @ exposeprivate string name; private int age; gson G = new gsonbuilder (). excludefieldswithoutexposeannotation (). create (); string pstr = G. tojson (p); for an instance whose P is person, only the name will be output and no name will be output. {"name ": "hsahga"} deserialization is the same as user defined exclusion strategies User-Defined discharge policy to solve hard-coding public class myexclusionstrategy implements exclusionstrategy {private class <?> [] Clazzs; // The Private string [] fileds array to be filtered out; // The attribute array public myexclusionstrategy (class <?> [] Clazzs, string [] fileds) {This. clazzs = clazzs; this. fileds = fileds;} public myexclusionstrategy (class <?> [] Clazzs) {This. clazzs = clazzs;} public myexclusionstrategy (string [] fileds) {This. fileds = fileds;} @ override public Boolean shouldskipclass (class <?> Clazz02) {If (this. clazzs = NULL) {return false;} For (INT I = 0; I <this. clazzs. length; I ++) {If (clazz02.getname (). equals (clazzs [I]. getname () {return true ;}} return false ;}@ override public Boolean shouldskipfield (fieldattributes f) {If (F = NULL) {return false ;} for (string field: This. fileds) {string [] STR = field. split ("_"); If (F. getdeclaringclass (). tostring (). equals (STR [1]) {If (STR [0]. equals (F. getname () {return true ;}} return false; // to use the annotation exclusion attribute, unseal the following section and block the following link: // return F. getannotation (noseriaizle. class )! = NULL; by annotation (@ noseriaizle)} or by annotation (@ noseriaizle) package inner; import Java. lang. annotation. elementtype; import Java. lang. annotation. retention; import Java. lang. annotation. retentionpolicy; import Java. lang. annotation. target; @ retention (retentionpolicy. runtime) @ target (elementtype. field) Public @ interface noseriaizle {} On the attribute to be used: @ noseriaizle private string name; Exclude name

 

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.