关闭

[置顶] jackson dynamic filter

标签: filterstringbeanpropertiesjsonimport
3376人阅读 评论(0) 收藏 举报
分类:
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonFilter;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;

/**
 *
 * @author Administrator
 */
@JsonFilter("myFilter")
class Bean {

    private String name = "2";

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    private int age = 3;

    public static void main(String[] args) throws IOException {
        Bean value = new Bean();


        // first, construct filter provider to exclude all properties but 'name', bind it as 'myFilter'
        ObjectMapper mapper = new ObjectMapper();
        FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter",
                SimpleBeanPropertyFilter.filterOutAllExcept(getFilter(value)));

        // and then serialize using that filter provider:
        String json = mapper.filteredWriter(filters).writeValueAsString(value);
        System.out.println(json);

    }

    private static Set<String> getFilter(Bean value) {
        Set<String> set = new HashSet();
        if (value.getName() != null) {
            set.add("name");
            // set.add("age");
        }
        return set;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:100054次
    • 积分:1411
    • 等级:
    • 排名:千里之外
    • 原创:57篇
    • 转载:1篇
    • 译文:0篇
    • 评论:14条
    文章分类
    最新评论