json-lib的一些過濾操作

來源:互聯網
上載者:User

標籤:

package demo4;import java.io.Serializable;import net.sf.json.JSONString;public class User implements JSONString,Serializable{    /**     *      */    private static final long serialVersionUID = 1L;    private long id;    private String name;    private String password;    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public User(long id, String name, String password) {        super();        this.id = id;        this.name = name;        this.password = password;    }        public User() {        super();    }        public String toJSONString() {        return "{\"id\":"+this.id+",\"name\":\""+this.name+"\"}";    }        }
user.java
package demo4;public class Teacher {    private int id;    private String name;    private String password;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public Teacher(int id, String name, String password) {        super();        this.id = id;        this.name = name;        this.password = password;    }    public Teacher() {        super();    }    }
Teacher.java
package demo4;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Date;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;import net.sf.json.JSONSerializer;import net.sf.json.JsonConfig;import net.sf.json.processors.JsonBeanProcessor;import net.sf.json.processors.JsonValueProcessor;import net.sf.json.util.PropertyFilter;import org.junit.Test;public class Demo {    /*         public void registerJsonBeanProcessor(Class target,                                      JsonBeanProcessor jsonBeanProcessor)    Registers a JsonBeanProcessor.    [Java -> JSON]    Parameters:        target - the class to use as key        jsonBeanProcessor - the processor to register              public void registerPropertyExclusion(Class target,    *註冊不轉換的屬性在類中 *                                      String propertyName)    Registers a exclusion for a target class.    [Java -> JSON]    Parameters:        target - the class to use as key        propertyName - the property to be excluded        public void setExcludes(String[] excludes)  設定不轉換的屬性        Sets the excludes to use.        Will set default value ([]) if null.        [Java -> JSON]                                     PropertyFilter: 屬性過濾器        一個方法:         apply    boolean apply(Object source,              String name,              Object value)    Parameters:        source - the owner of the property        name - the name of the property        value - the value of the property     Returns:        true if the property will be filtered out, false otherwise     */            /**     * 忽略不必要屬性重寫該對象指定toJSONString方法測試     */    @Test    public void fun(){        User user=new User(12,"郭大俠","gz1234");        JSONObject jo=JSONObject.fromObject(user);        System.out.println(jo);    }        /**     * 忽略不必要的屬性,使用jsonConfig實現     * 通過jsonconfig執行個體,對包含和需要排除的屬性進行方便的添加或刪除     */    @Test    public void fun1(){        Teacher t=new Teacher(12,"guodaxia","gz1234");        JsonConfig config=new JsonConfig();        config.setExcludes(new String[]{"password"});//設定排除password屬性        JSONObject jo=JSONObject.fromObject(t, config);        System.out.println(jo);    }        /**     * 測試使用屬性過濾器達到前面的效果     * 使用propertyFilter可以允許同時對需要排除的屬性和類進行控制,這種控制還可以是雙向的,也可以應用到json字串到java對象     */    @Test    public void fun2(){        Teacher t=new Teacher(12,"guodaxia","gz1234");        JsonConfig config=new JsonConfig();        config.setJsonPropertyFilter(new PropertyFilter() {                        public boolean apply(Object source, String propertyName, Object value) {                /**                 * 就這樣將Teacher類中的password屬性過濾掉了                 *///                return source instanceof Teacher && "password".equalsIgnoreCase(propertyName);                return  "password".equalsIgnoreCase(propertyName);//這個是測試它可以雙向過濾            }                    });        JSONObject jo=JSONObject.fromObject(t, config);        System.out.println(jo);        JSONObject jo1=(JSONObject) JSONSerializer.toJSON("{‘id‘:12,‘name‘:‘gz‘,‘password‘:‘a12345‘}", config);//這裡使用JSONSerializer得到的JSON對象才有效可轉換為Teacher對象,JSONObject.fromObject不行,不知為何        Teacher tt=(Teacher) jo1.toBean(jo1, Teacher.class );        System.out.println(tt.getId()+"--"+tt.getName()+"--"+tt.getPassword());        //        JSONObject jo1=JSONObject.fromObject("{‘id‘:12,‘name‘:‘gz‘,‘password‘:‘a12345‘}",config);//        Object tt=  JSONObject.toBean(jo1);//        System.out.println(tt);            }        /**     * 使用registerPropertyExclusion達到前面的效果     */    @Test    public void fun3(){        Teacher t=new Teacher(12,"guodaxia","gz1234");        JsonConfig config=new JsonConfig();        config.registerPropertyExclusion(Teacher.class, "password");        JSONObject jo=JSONObject.fromObject(t, config);        System.out.println(jo);            }        /**     * 測試使用自訂JSONBeanProcessor     * JsonBeanProcessor和實現JsonString很類似,返回一個代表原來目標對象的合法JSONObject     *      */    @Test    public void fun4(){        JsonConfig config=new JsonConfig();        config.registerJsonBeanProcessor(Teacher.class,new JsonBeanProcessor() {                        public JSONObject processBean(Object bean, JsonConfig config) {                Teacher tea=(Teacher)bean;                return new JSONObject().element("id", tea.getId()).element("name", tea.getName());            }        });        Teacher t=new Teacher(12,"JSON","json");        System.out.println(JSONObject.fromObject(t,config));                    }        /**     * 自訂JsonValueProcessor     * 比如我們要控制JSON序列化過程中的Date對象的格式化以及數值的格式化,JsonValueProcessor是最好的選擇     * 該方法可以用來處理資料,進行格式化操作等等     */    @Test    public void fun5(){        Map<String,Object> map=new HashMap<String,Object>();        map.put("date", new Date());        map.put("dates", Arrays.asList(new Date()));        JsonConfig config=new JsonConfig();        config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {            //自訂日期處理格式            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");                        /**             *處理單個Date對象              */            public Object processObjectValue(String propertyName, Object date, JsonConfig config) {                return sdf.format(date);            }                        public Object processArrayValue(Object date, JsonConfig config) {                return sdf.format(date);            }        });        System.out.println(JSONObject.fromObject(map, config));            }        }

 

json-lib的一些過濾操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.