问题
如何指示ObjectMapper
他应该按某些条件(字段)过滤对象的嵌套集合。请参阅代码说明:
通过代码解释:
我必须Container
对象转换为 JSON。但我想根据Entry.value
字段过滤entries
集合。我的意思是我想序列化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);
}
你可以Entry
实现JsonSerializable
。在杰克逊 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>
并在序列化之前注册它;它基本上与上述相同。