1

I create a cuztom serializer for superclass, then all subclass serialized without it's own fields.


class Super{
   double f1;
}

class Sub extends Super{
   double f2;
}

class CuztomSerializer extends StdSerializer<Super>{
   @Override
    public void serialize(Super s, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField("f1", BigDecimal.valueOf(s.getF1()).setScale(2, RoundingMode.FLOOR));
        gen.writeEndObject();
    }
}

As the codes above, Sub instance serialized only has f1 field. How to reserve f2 field?

Z fp
  • 562
  • 5
  • 20
  • hi perhaps this might be of interest https://stackoverflow.com/questions/44110624/need-jackson-serializer-for-double-and-need-to-specify-precision-at-runtime – jspcal Mar 11 '22 at 03:16
  • @jspcal thx. it helps in this demo, but in my real business, the CustomSerializer do more work actually, setting serialization precision maybe not enough. – Z fp Mar 11 '22 at 03:26
  • Why don't you custom serialize `f1` instead of the entire object? – shmosel Mar 11 '22 at 03:29
  • @shmosel that's only a simple demo to show my problem. In real business the custom serializer is more complex. – Z fp Mar 11 '22 at 03:36
  • I'm not sure what exactly you're trying to say, but if the problem is more complex than you're describing, how do you expect us to help you? – shmosel Mar 11 '22 at 23:20
  • @shmosel I just want to know if it is possible to make subclass fields serialized in this situation by some settings? If not, I would consider other way instead of serializer for entire superclass. Sorry for my poor english, hope I have expressed my intent clearly. – Z fp Mar 12 '22 at 07:16

0 Answers0