Home > OS >  Handle retrocompatility when changing cardinality with spring mvc
Handle retrocompatility when changing cardinality with spring mvc

Time:12-24

I have an existing service created with SpringMvc. He is already used and accept an object like that :

  public class MyDto{
   private AType a;
   private BType b;

   //and corresponding getters and setters
   
 }

and corresponding Json

{
   a: {},
   b: {}
}

And i want to change the cardinality of A to :

  public class MyDto{
   private List<AType> a;
   private BType b;

   //and corresponding getters and setters
   
 }

and the corresponding json :

{
   a: [{}],
   b: {}
}

But i want to continue to accept the json from the first representation because i can't easily update all the consumer of my api.

My first idea was to create a version 2 of my api because this is breaking change. But i think this too much because if the api consumer send one element i can just create a list of one element.

But i don't know if i can do that with spring mvc.

CodePudding user response:

Yes, I think it's ok if you use @JsonDeserialize with few customize.

public class MyDto{
   @JsonDeserialize(using = CustomDeserializer.class)
   private List<AType> a;
   private BType b;

   //and corresponding getters and setters
   
 }

And here is CustomDeserializer

public class CustomDeserializer extends JsonDeserializer<List<AType>> {
    @Override
    public List<AType> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {      
        if(jsonParser.isExpectedStartObjectToken()){
            final AType aType = jsonParser.readValueAs(new TypeReference<AType>() {});
            return Arrays.asList(aType);
        }
        return jsonParser.readValueAs(new TypeReference<List<AType>>() {}); 
    }
}

My idea is simple: If json start with Object Token, we convert it to AType and add to List then return list. If not, it must start with array, we will convert it to List

Sorry for any typo mistake because i am using notepad .

  • Related