Gson library uses-Sort field (exclusionstrategy) or modify (fieldnamingstrategy) Field

Source: Internet
Author: User

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 ();}}

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.