2011-11-22 47 views
7

有没有办法在ObjectMapper中注册全局属性过滤器?全局意味着它将被应用于所有序列化的bean。我不能使用注释(我不能修改序列化的bean),也不知道bean有什么属性。 过滤应该是基于名称的。全球房产过滤杰克逊

我的第一个想法是写一个自定义序列化程序,但我不知道应该传递给构造函数。

回答

9

我会使用FilterProvider。这有点牵扯,但不太笨拙。

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; 
import org.codehaus.jackson.annotate.JsonMethod; 
import org.codehaus.jackson.map.ObjectMapper; 
import org.codehaus.jackson.map.ObjectWriter; 
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; 

public class JacksonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    Bar bar = new Bar(); 
    bar.id = "42"; 
    bar.name = "James"; 
    bar.color = "blue"; 
    bar.foo = new Foo(); 
    bar.foo.id = "7"; 
    bar.foo.size = "big"; 
    bar.foo.height = "tall"; 

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY); 
    System.out.println(mapper.writeValueAsString(bar)); 
    // output: 
    // {"id":"42","name":"James","color":"blue","foo":{"id":"7","size":"big","height":"tall"}} 

    String[] ignorableFieldNames = { "id", "color" }; 

    FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames)); 

    mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY); 
    mapper.getSerializationConfig().addMixInAnnotations(Object.class, PropertyFilterMixIn.class); 
    ObjectWriter writer = mapper.writer(filters); 

    System.out.println(writer.writeValueAsString(bar)); 
    // output: 
    // {"name":"James","foo":{"size":"big","height":"tall"}} 
    } 
} 

@JsonFilter("filter properties by name") 
class PropertyFilterMixIn 
{ 

} 

class Bar 
{ 
    String id; 
    String name; 
    String color; 
    Foo foo; 
} 

class Foo 
{ 
    String id; 
    String size; 
    String height; 
} 

对于其他方法和更多信息,我推荐以下资源。

+0

像一个魅力的作品:)有在杰克逊文档改进了很多地方。 – DAN

+0

为了感兴趣,我在http://jira.codehaus.org/browse/JACKSON-724上登录了一个增强请求,以简化按名称过滤属性所需的配置。 –

+0

@DAN绝对!文稿特别受欢迎! (包括好文章链接,wiki更新) – StaxMan