Gson is very powerful in parsing JSON data, but sometimes it is troublesome to use it improperly.
1 "cyclic serialization" Exception
The solution is to add transient to fields that may cause loop serialization.
Transient private menu parent; // parent node
2. Sort specific fields
For example, if the JSON data of a user is {ID: "1", name: "syxchina", password: "syx"}, we do not want to parse the password during parsing, the format is {ID: "1", name: "syxchina "}.
The first method is to use the annotation provided by gson, but the field that does not have any data at any time.
The second method uses gsonbuilder to set the exclusionstrategy parameter.
// Original string: {ID: "1", name: "syx", password: "syx"} // effect: {ID: "1", Name: "syx"} Private Static gson gsonmenucombotree = new gsonbuilder ()//. setexclusionstrategies (New menutreeexclusionstrategy ())//. create (); Private Static class menutreeexclusionstrategy implements exclusionstrategy {public Boolean shouldskipfield (fieldattributes f) {If ("password ". equals (F. getname () return true; return false;} public Boolean Shouldskipclass (class <?> Clazz) {return false ;}}
3. Modify the JSON field display.
// JSON: {ID: "1", name: "syx", password: "syx "}
// Out: {ID: "1", name: "syx", modifyfield: "syx"} Private Static gson gsonmenucombotree = new gsonbuilder ()//. setfieldnamingstrategy (New menutreefieldnamingstrategy ())//. create ();
Private Static class menutreefieldnamingstrategy implements fieldnamingstrategy {Public String translatename (field F) {If ("password ". equals (F. getname () {return "modifyfield";} return F. getname ();}}