0

When using jackson serialization, field b is ignored when field a is false

public class MyClass {
    private boolean a;
    private int b;
}

I haven't found a solution yet,Trying to use @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = AlarmConfig.TrueFilter.class) only works for single field

MiaoZi
  • 3
  • 2
  • This is just a bad idea. Instead, set `b` to `null` and have Jackson ignore null values instead. Added bonus: You probably won't even need `a` at all any more (just check `b != null`) – Jorn Jul 18 '23 at 11:13
  • You can try to use `@JsonAnyGetter` annotation and implement a method which checks any conditions and return as many different fields as you want. Take a look on this example [Jackson diffrent name base of other field value](https://stackoverflow.com/a/75044947/51591) – Michał Ziober Jul 18 '23 at 23:00

1 Answers1

0

You may create your own serializer, something like:

public class MyClassSerializer extends JsonSerializer<MyClass> {

    @Override
    public void serialize(MyClass value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeBooleanField("a", value.isA());
        if (value.isA()) {
            gen.writeNumberField("b", value.getB());
        }
        gen.writeEndObject();
    }
}

and use it like:

@JsonSerialize(using = MyClassSerializer.class)
public class MyClass { ... }
Yahor Barkouski
  • 1,361
  • 1
  • 5
  • 21