Gson is a JSON serialization/deserialization tool released by Google that is very easy to use. This article briefly discusses how to exclude certain fields when you use Gson to turn Java objects into JSON.
The simplest usage
Suppose you have the following class:
1 classMYOBJ {2 3 Public intx;4 Public inty;5 6 PublicMYOBJ (intXinty) {7 This. x =x;8 This. y =y;9 }Ten}
The simplest Gson usage is as follows:
@Test Public void Gson () { new MyObj (1, 2); New Gson (). ToJson (obj); Assert.assertequals ("{\" x\ ": 1,\" y\ ": 2}", JSON); }
Method 1: Exclude the Transient field
The simplest way to do this is to add the transient modifier to the field as follows:
classMYOBJ { Public transient intX//<--- Public inty; PublicMYOBJ (intXinty) { This. x =x; This. y =y; }} @Test Public voidGson () {MyObj obj=NewMYOBJ (1, 2); String JSON=NewGson (). ToJson (obj); Assert.assertequals ("{\" y\ ": 2}", JSON);//<---}
Method 2: Exclude modifier as a field of the specified type
This method requires Gsonbuilder to customize a Gson instance as follows:
classMYOBJ {protected intX//<--- Public inty; PublicMYOBJ (intXinty) { This. x =x; This. y =y; }} @Test Public voidGson () {Gson Gson=NewGsonbuilder (). Excludefieldswithmodifiers (modifier.protected)//<---. Create (); MYOBJ obj=NewMYOBJ (1, 2); String JSON= Gson.tojson (obj);//<---Assert.assertequals ("{\" y\ ": 2}", JSON);}
Method 3: Use @expose annotations
Note that fields that are not labeled @Expose are excluded, as follows:
classMYOBJ { Public intx; @Expose Public intY//<--- PublicMYOBJ (intXinty) { This. x =x; This. y =y; }} @Test Public voidGson () {Gson Gson=NewGsonbuilder (). Excludefieldswithoutexposeannotation ()//<---. Create (); MYOBJ obj=NewMYOBJ (1, 2); String JSON=Gson.tojson (obj); Assert.assertequals ("{\" y\ ": 2}", JSON); }
Method 4: Use the Exclusionstrategy custom field exclusion policy
This is the most flexible approach, and the following example removes all fields starting with the underscore:
classMYOBJ { Public int_x;//<--- Public inty; PublicMYOBJ (intXinty) { This. _x =x; This. y =y; }} @Test Public voidGson () {exclusionstrategy myexclusionstrategy=NewExclusionstrategy () {@Override Public BooleanShouldskipfield (FieldAttributes fa) {returnFa.getname (). StartsWith ("_"); } @Override Public BooleanShouldskipclass (class<?>clazz) { return false; } }; Gson Gson=NewGsonbuilder (). Setexclusionstrategies (Myexclusionstrategy)//<---. Create (); MYOBJ obj=NewMYOBJ (1, 2); String JSON=Gson.tojson (obj); Assert.assertequals ("{\" y\ ": 2}", JSON); }
From http://blog.csdn.net/zxhoo/article/details/21471005