Question

Question How to indicate ObjectMapperthat he should filter object's nested collection by some criteria (field). See explanation via code:

Explanation via code:

I have to convert Container object to JSON. But I want to filter entries collection based on Entry.value field. I mean I want to serialize Container and include only that Entries which 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);
}
Was it helpful?

Solution

You can make Entry implement JsonSerializable. In Jackson 2.x it will give:

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);
    }
}

Another solution would be to implement a custom JsonSerializer<Entry> and register it before you serialize; it would basically do the same as the above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top