Jackson-databind: Accessing Context of Serializing Object from Serializer

Created on 20 Aug 2013  路  5Comments  路  Source: FasterXML/jackson-databind

public class UserProfile{
   Integer userId;

   Gender gender;

   @JsonPhotoUserUrl
   Integer photoId;
}

@Retention(RetentionPolicy.RUNTIME)
@JsonProperty("photoUrl")
@JsonSerialize(using = JsonPhotoUserUrlSerializer.class)
public @interface JsonPhotoUserUrl {

}

We would like to serialize photoId as a URL. However there are some users who have not a photo yet and for these conditions we would like to show a default picture according to gender. For this case we desperately need the gender.

Please provide a way to access object which is being serialized.

Most helpful comment

It looks like some generic context passing mechanism would be very useful.
I need to serialize a field depending on the information not inherent to the object(s) being serialized but to the thread that is serializing.
For instance, I have a message object with payload and headers, I'd like to convert its payload to JSON (or back) with some fields represented in different format (like string literal or numeric value for Enums) depending on the initial message header value, which is not part of the object tree being converted.
Creating a new ObjectMapper with custom (de)serializers for each message to achieve the goal looks expensive.

All 5 comments

By 'object which is being serialized' are you referring to the object that refers to value being serialized ("parent" so to speak)?

In example above, I assume @JsonPhotUserUrl is missing annotation bundle annotation.

I was referring UserProfile instance by _parent_ word while photoId field is serialized by _JsonPhotoUserUrlSerializer_.

Sorry for forgotten annotation also. I had to write without using an editor. If you want, I can also prepare a few test cases regarding this to make it clearer.

It looks like some generic context passing mechanism would be very useful.
I need to serialize a field depending on the information not inherent to the object(s) being serialized but to the thread that is serializing.
For instance, I have a message object with payload and headers, I'd like to convert its payload to JSON (or back) with some fields represented in different format (like string literal or numeric value for Enums) depending on the initial message header value, which is not part of the object tree being converted.
Creating a new ObjectMapper with custom (de)serializers for each message to achieve the goal looks expensive.

I agree that context passing would be useful. Question then is that of what aspects to cover (simple key/value pairs should be simple, for example), and how to expose it.

Actually, #631 does this with 2.5.0 (due to release soon).

Was this page helpful?
0 / 5 - 0 ratings