FasterXml:过​​滤器集合

时间:2014-02-25 12:34:05

标签: java json fasterxml

问题 如何指出ObjectMapper他应该按某些条件(字段)过滤对象的嵌套集合。通过代码查看说明:

通过代码解释:

我必须将Container对象转换为JSON。但我想基于entries字段过滤Entry.value集合。我的意思是我想序列化Container并仅包含value == 1

的条目
public class Container {  
  List<Entry> entries;

  public void setEntries(List<Entry> entries) {
    this.entries = entries;
  }
}

public class Entry {
  int value;

  public Entry(int value) {
    this.value = value;
  }
}


public static void main(String[] args) {
  ObjectMapper mapper = new ObjectMapper();
  Container container = new Container();
  container.setEntries(new LinkedList<Entry>({
    {
      add(new Entry(1));
      add(new Entry(2));
      add(new Entry(1));
    }
  }))
  // Now I want to get container object only with two elements in list
  mapper.writeValueAsString(container);
}

1 个答案:

答案 0 :(得分:2)

您可以Entry实施JsonSerializable。在Jackson 2.x中,它会给出:

public class Entry
    implements JsonSerializable
{
    int value;

    public Entry(int value) 
    {
        this.value = value;
    }

    @Override
    public void serialize(final JsonGenerator jgen,
        final SerializerProvider provider)
        throws IOException
    {
        // Don't do anything if value is not 1...
        if (value != 1)
            return;

        jgen.writeStartObject();
        jgen.writeNumberField("value", 1);
        jgen.writeEndObject();
    }

    @Override
    public void serializeWithType(final JsonGenerator jgen,
        final SerializerProvider provider, final TypeSerializer typeSer)
        throws IOException
    {
        serialize(jgen, provider);
    }
}

另一个解决方案是实现自定义JsonSerializer<Entry>并在序列化之前注册它;它基本上和上面一样。