How to add derived properties to a Jackson 2 serialized class?

前端 未结 2 1289
予麋鹿
予麋鹿 2021-01-23 09:20

I\'m serializing some existing objects with Jackson 2.22, leveragin the MixIn feature to decouple the real object from the Jackson annotations configuration.

Actually my

2条回答
  •  借酒劲吻你
    2021-01-23 09:37

    Here's how I did it.

    The solution is to specify a custom JsonSerializer implementation to the field getter.

    First of all, I changed the mixin interface to a class that extends the entity (target) class, so that it can access the target class data.

    public class ProductApi extends Product {
    
        @JsonProperty
        @Override
        public String getName() {
            return super.getName();
        };
    
        // ...
    
    }
    

    Next, I implemented the JsonSerializer that would create the derived property I want:

    public static class ImagesSerializer extends JsonSerializer {
    
        @Override
        public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            Product p = (Product) jgen.getCurrentValue();
    
            int num = p.getNumberOfImages();
    
            List imgs = new ArrayList(num);
    
            for(int i = 0; i < num; i++) {
                String src = "/include/images/showImage.jsp?"+"id="+p.getId()+"&number="+i;
                imgs.add(src);
            }
    
            provider.defaultSerializeValue(imgs, jgen);
        }
    
    }
    

    This is a really simple implementation, more safety checks should be done.

    What this does is, basically, retrieve the whole entity instance from the JSON generator, build up a custom object and then ask Jackson to serialize it.
    I implemented it inside my ProductApi as a static class, but just for simplicity.

    Finally, the serializer needs to be bound to the JsonProperty annotated field:

    public class ProductApi extends Product {
    
        @JsonProperty
        @Override
        public String getName() {
            return super.getName();
        };
    
        // ...
    
        @JsonSerialize(using=ImagesSerializer.class)
        @JsonProperty("images")
        @Override
        public String getImage() { // in my entity this returns an image number, whereas in my JSON I want a list of URLs
            return "";
        }
    
        // ...
    
    }
    

    As a side note, it seems that the returned value of the getImage() method is not used.

提交回复
热议问题