0

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 ?

Ajeet Ganga
  • 8,353
  • 10
  • 56
  • 79

2 Answers2

0

have you try to add the @JsonIgnoreProperties(ignoreUnknown = true) on your domain object?

  • I am not the consumer of 'GET /services/v1/myobject` I am producer of it. – Ajeet Ganga Feb 26 '17 at 03:33
  • have you try using Java Generic type? such as @JsonIgnoreProperties(ignoreUnknown = true) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class MyEntity { private String version; private T VersionedEntity; } – Mary Zheng Feb 27 '17 at 02:00
0

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);
    
Ajeet Ganga
  • 8,353
  • 10
  • 56
  • 79