dev_feed
dev_feed

Reputation: 719

If a java pojo is declared as an object, how do you control jackson serialization based on the run time type?

For example, if I declare a Map<String,Object> with a mixed type value set and I try to serialize with a custom TypeResolverBuilder, I don't have access to the run time type of the value.

But if I want to write type information for some of the values and not others, how can that be accomplished? I've been reading into the DefaultSerializerProvider and it seems to ignore the run time type and just use the JavaType (which is Object.class)

We're using Jackson 2.9

Upvotes: 2

Views: 65

Answers (1)

Joe W
Joe W

Reputation: 2891

If you are able to edit your POJOs where you need to control the output you should be able to extend JsonSerializer and only write the information you want in the output of the serialize method.

You could also be able to annotate your map to provide a custom serializer and interogate the object to be serialized using instanceof

@JsonSerialize(keyUsing = SpecialSerializer.class) 
Map<String, Object> map;

And then in your serializer:

 @Override
    public void serialize(Object value, 
      JsonGenerator gen,
      SerializerProvider serializers) 
      throws IOException, JsonProcessingException {
           if(value instanceof MySpecialObject){

                 //special logic here
          }
    }

Upvotes: 3

Related Questions