You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jackson Filter排除Java类列表字段中的指定对象

Got it, let's tackle this problem step by step. You want to exclude any child objects where the done property equals 1 when serializing your Java class to JSON using Jackson. Here are a couple of solid approaches that should work reliably:

1. Filter Directly in the Getter (Quickest Fix)

If your filtering rule is static and you don't need fancy Jackson-specific logic, this is the simplest way. Just modify the getter for your children list to return only the objects that meet your criteria:

public class Parent {
    private String name;
    private List<Child> children;

    // Other getters/setters
    public List<Child> getChildren() {
        // Filter out any child where done == 1
        return children.stream()
                .filter(child -> child.getDone() != 1)
                .collect(Collectors.toList());
    }
}

Note: This creates a new filtered list every time the getter is called. For small datasets, this is totally fine, but keep an eye on performance if you're dealing with huge lists.

2. Custom JsonSerializer (More Control)

If you want to keep your domain class clean and handle the filtering purely during serialization, a custom serializer is the way to go.

First, assume your basic class structure looks like this:

public class Parent {
    private String name;
    private List<Child> children;
    // Getters and setters
}

public class Child {
    private String id;
    private int done;
    // Other fields, getters and setters
}

Create a serializer that handles the filtering for the children list:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class FilteredChildrenSerializer extends JsonSerializer<List<Child>> {
    @Override
    public void serialize(List<Child> children, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        // Apply your filter logic here
        List<Child> filteredKids = children.stream()
                .filter(child -> child.getDone() != 1)
                .collect(Collectors.toList());
        // Serialize the filtered list normally
        gen.writeObject(filteredKids);
    }
}

Then annotate the children field in your Parent class to use this serializer:

public class Parent {
    private String name;
    
    @JsonSerialize(using = FilteredChildrenSerializer.class)
    private List<Child> children;

    // Getters and setters
}

Now whenever Jackson serializes a Parent object, it will automatically exclude any Child with done == 1 from the children array.

3. Using @JsonFilter (Dynamic Filtering)

If you need to switch filtering rules dynamically (e.g., sometimes include done=1, sometimes not), use Jackson's filter system.

First, add the @JsonFilter annotation to your Parent class:

@JsonFilter("childFilter")
public class Parent {
    private String name;
    private List<Child> children;
    // Getters and setters
}

Create a custom filter that handles the list filtering:

import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import java.util.List;
import java.util.stream.Collectors;

public class ChildFilter extends SimpleBeanPropertyFilter {
    @Override
    public void serializeAsField(Object pojo, JsonGenerator gen, SerializerProvider prov, PropertyWriter writer) throws Exception {
        if (writer.getName().equals("children") && pojo instanceof Parent) {
            Parent parent = (Parent) pojo;
            List<Child> filtered = parent.getChildren().stream()
                    .filter(child -> child.getDone() != 1)
                    .collect(Collectors.toList());
            // Write the filtered list to JSON
            gen.writeFieldName(writer.getName());
            gen.writeObject(filtered);
        } else {
            // Serialize other fields normally
            super.serializeAsField(pojo, gen, prov, writer);
        }
    }
}

Finally, register the filter when you serialize your object:

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // Set up the filter provider
        FilterProvider filterProvider = new SimpleFilterProvider()
                .addFilter("childFilter", new ChildFilter());
        
        // Create your parent object and populate data
        Parent parent = new Parent();
        // ... add children, some with done=1
        
        // Serialize with the filter
        String json = mapper.writer(filterProvider).writeValueAsString(parent);
        System.out.println(json);
    }
}

Which Approach Should You Pick?

  • Getter Filter: Best for simple, static rules and minimal code changes.
  • Custom Serializer: Ideal when you want to keep domain logic separate from serialization logic.
  • @JsonFilter: Perfect for dynamic scenarios where you need to adjust filtering on the fly.

内容的提问来源于stack exchange,提问作者Nik391

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:53:07