billroper: (Default)
[personal profile] billroper
This turned out to be really simple, but it was really difficult to find this as I was digging through the information on Jackson serialization, so I'm going to mention it here in case it's of use to anyone else.

I have some Java classes that are IDs that we cache so that (if everything goes right) everyone shares one copy of the immutable ID. They can all be represented as a Java String and there is a static valueOf() method in each ID class that either fetches a value from the cache or creates a new value in the cache if you're the first to request this ID. The toString() method generates the String from the ID.

So when you're serializing a bunch of JSON or XML, you want to write out the simple String representation and read in the String on the opposite side and then use it to fetch an ID from the cache instead of creating a new instance of the ID. It turns out that you can do this with just *two* Jackson annotations.

You tag the toString() method with the @ JsonValue annotation. This tells the Jackson framework that this is the only value that they need to serialize out to describe the contents of this class.

For the inbound side of the serialization, you tag the valueOf() method with the @ JsonCreator annotation so that the Jackson framework knows to call that method instead of a constructor.

Two annotations and it all works.

Cool!

Profile

billroper: (Default)
billroper

May 2025

S M T W T F S
     1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 2324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 24th, 2025 04:25 pm
Powered by Dreamwidth Studios