0

问题如何指示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);
}
4

1 回答 1

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>另一种解决方案是在序列化之前实现自定义并注册它;它基本上与上述相同。

于 2014-02-25T12:48:00.047 回答