0

I need to write a custom Jackson JSON serializer for a class that does the following:

  • If the object isCustomJSON(), it should be encoded as string "CUSTOM" (obviously, assuming the object's class has a Boolean isCustomJSON() method)
  • If the object isn't isCustomJSON(), it should be encoded using default Jackson JSON serializer for its class that would have been used if it didn't have a registered custom serializer.

I'm guessing the code would look like this:

public class ItemSerializer extends StdSerializer<Item> { // Add boilerplate
    @Override
    public void serialize (
        Item value, JsonGenerator jgen, SerializerProvider provider) { // add throws
        if (value.isCustomJSON()) {
            jgen.writeString("CUSTOM");
        } else {
            jgen.NeedToWriteStandardEncodedJSONSerialization(value);
            // PROFIT??? 
        }
    }
}

How do I implement jgen.NeedToWriteStandardEncodedJSONSerialization(value); piece?


Side note: just in case I'm wrestling with an X-Y problem, the reason behind doing this weird logic is that I need to add support for old API in my code, which expects different JSON encoding from the default one that my class structure currently provides, due to class restructuring in the server (old code can't be changed to include new class structure). My approach is to: 1. detect old API request; 2. flag it as old API in the data via isCustomJSON() and 3. write custom Jackson JSON serializer which outputs JSON that old API can understand; while letting requests from new API use default normal JSON serializer default for that class. Even if it is an X-Y problem; please center your answers around "how to technically achieve what you asked" since I want to know the answer not only to solve the problem but also to improve my knowledge of Jackson

DVK
  • 126,886
  • 32
  • 213
  • 327

0 Answers0