问题 如何指出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);
}
答案 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>
并在序列化之前注册它;它基本上和上面一样。