1

When converting json string to object using ObjectMapper I want to validate that it should only convert it to Object only when all the json keys match with that of Class. Eg:

Class ABC{
   private String mem1;
   private String mem2;
   private String mem3;
}

lets say the json string is

{
    mem1:'somevalue',
    mem3:'somevalue'
}

when using object mapper to convert above json string to class ABC it will convert as it matches mem1 and mem3, I want to validate such that it converts if the json string has all the three members as that of class ABC.

Any idea on how to do it? The only way I can think of is converting json string into JSONObject and then match the keys with the field name of the class

  • I needed similar solution, hence you can go through of this thread, I think it will help: [How to throw exception while converting from JsonStr to PojoClassObj if any key/value is missing in the JsonStr?](https://stackoverflow.com/questions/44362030/how-to-throw-exception-while-converting-from-jsonstr-to-pojoclassobj-if-any-key) – user404 Mar 09 '20 at 10:55

1 Answers1

1

This would do:

class Abc{
    private String mem1;
    private String mem2;
    private String mem3;

    @JsonCreator
    public Abc(@JsonProperty(value = "mem1", required = true) String mem1
            , @JsonProperty(value = "mem2", required = true)String mem2
            , @JsonProperty(value = "mem3", required = true)String mem3) {
        this.mem1 = mem1;
        this.mem2 = mem2;
        this.mem3 = mem3;
    }
}
Neeraj
  • 2,376
  • 2
  • 24
  • 41
  • This would indeed help and would work like charm if used with new spring standards. But my code is a legacy one and I am having autowired fields and setter based injections – Akshay Srivastava Mar 09 '20 at 16:22