restserializationpojoannotated-pojos

Conditional naming of POJO classes


Our problem is, our service GET /services/v1/myobject returns object named Xyz. This representation is used by multiple existing clients.

The new service GET /services/v2/myobject needs to expose exact same object but with different name, say XyzLmn

Now one obvious solution would be to create two classes Xyz and XyzLmn, then copy Xyz into XyzLmn and expose XyzLmn in the v2.

What I am looking for is, how can I keep the same java pojo class Xyz and conditionally serialize it to either XyzLmn or Xyz ?


Solution

  • One solution is:

    1. Write a customer serializer that emits XyzLmn
    2. Register the customer serializer conditionally

      public class XyzWrapperSerializer extends StdSerializer<Item> {
      
      public ItemSerializer() {
          this(null);
      }
      
      public ItemSerializer(Class<Item> t) {
          super(t);
      }
      
      @Override
      public void serialize(
        Item value, JsonGenerator jgen, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
      
          jgen.writeStartObject();
          jgen.writeNumberField("XyzLmn", value.id);
          jgen.writeEndObject();
      } }
      
      XyzWrapper myItem = new XyzWrapper(1, "theItem", new User(2, "theUser"));
      ObjectMapper mapper = new ObjectMapper();
      
      SimpleModule module = new SimpleModule();
      module.addSerializer(XyzWrapper.class, new XyzWrapperSerializer());
      mapper.registerModule(module);
      
      String serialized = mapper.writeValueAsString(myItem);