We often selectively filter out some of the property values when we switch between a JSON string and a Java object. For example, the following class:
1 Public class Person2 {3 PrivateString name;4 PrivateString address;5 PrivateString sex;6 7 PublicString getaddress ()8 {9 returnaddress;Ten } One A Public voidsetaddress (String address) - { - This. Address =address; the } - - PublicString getName () - { + returnname; - } + A Public voidsetName (String name) at { - This. Name =name; - } - - PublicString getsex () - { in returnsex; - } to + Public voidsetsex (String sex) - { the This. Sex =sex; * } $}
View Code
What if I want to filter the address attribute?
Method One: Implement the Jsonstring interface
1 Importnet.sf.json.JSONString;2 Public classPersonImplementsjsonstring3 {4 PrivateString name;5 PrivateString sex;6 PrivateString address;7 PublicString tojsonstring ()8 {9 return"{\" name\ ": \" "+ name +" \ ", \" sex\ ": \" "+ Sex +" \ "}";Ten } One PublicString getaddress () A { - returnaddress; - } the Public voidsetaddress (String address) - { - This. Address =address; - } + PublicString getName () - { + returnname; A } at Public voidsetName (String name) - { - This. Name =name; - } - PublicString getsex () - { in returnsex; - } to Public voidsetsex (String sex) + { - This. Sex =sex; the } * } $ ImportNet.sf.json.JSONObject;Panax Notoginseng Public classTest { - Public Static voidMain (String args[]) { thePerson person =NewPerson (); +Person.setname ("Swiftlet"); APerson.setsex ("Men"); thePerson.setaddress ("China"); +Jsonobject JSON =Jsonobject.fromobject (person); - System.out.println (json.tostring ()); $ } $}
View CodeMethod Two: Set the Jsonconfig instance to add or remove attributes that contain and need to be excluded.
1 ImportNet.sf.json.JSONObject;2 ImportNet.sf.json.JsonConfig;3 Public classTest4 {5 Public Static voidMain (String args[])6 {7Person person =NewPerson ();8Person.setname ("Swiftlet");9Person.setsex ("Men");TenPerson.setaddress ("China"); OneJsonconfig Jsonconfig =Newjsonconfig (); AJsonconfig.setexcludes (Newstring[] -{"Address" }); -Jsonobject JSON =Jsonobject.fromobject (person, jsonconfig); the System.out.println (json.tostring ()); - } -}
View CodeMethod Three: Use the PropertyFilter instance to filter the properties.
1 ImportNet.sf.json.JSONObject;2 ImportNet.sf.json.JsonConfig;3 ImportNet.sf.json.util.PropertyFilter;4 Public classTest5 {6 Public Static voidMain (String args[])7 {8Person person =NewPerson ();9Person.setname ("Swiftlet");TenPerson.setsex ("Men"); OnePerson.setaddress ("China"); AJsonconfig Jsonconfig =Newjsonconfig (); -Jsonconfig.setjsonpropertyfilter (NewPropertyFilter () { - Public Booleanapply (object source, String name, object value) the { - returnSourceinstanceofPerson && name.equals ("Address"); - } - }); +Jsonobject JSON =Jsonobject.fromobject (person, jsonconfig); - System.out.println (json.tostring ()); + } A}
View Code
JSON tutorial Series (3)-jsonobject filter settings