Home > other >  Spring Jackson validate input field is a valid JSON
Spring Jackson validate input field is a valid JSON

Time:02-24

Have a pojo which is suppled via a rest call. One of the fields of the pojo is a JSON. The JSON can be any valid JSON. It is a Run Time value supplied by a couple of different inputs. The goal is to throw an exception if the JSON field is not a valid JSON

Have tried: In POJO

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
private JsonNode json;

Have also tried using

@JsonRawValue

However when I supply anything it picks it up as a node of some type (TestNode, IntNode) etc.

anyway to do the validation without introduction of extra code? If not how to check at the controller when the object comes in?

CodePudding user response:

One way to do this is use org.springframework.validation.Validator You can annotate your controller with

@PostMapping("/abc")
public Test test((@Validated(YourValidator.class) 
     @RequestBody YourPojo pojo)) {
        return test;
   }

Now you can write your own validation

    public class YourValidator implements org.springframework.validation.Validator {
    
       
    
        @Override
        public void validate(Object target, Errors errors) {
            YourPojo pojo = (YourPojo) target;
             boolean validJson =false;
           
    try {
           final ObjectMapper mapper = new ObjectMapper(); //jackson library
       String jsonInString = pojo.getJsonField() ;
   mapper.readTree(jsonInString);
           validJson= true;
        } catch (IOException e) {
           validJson= false;
        }
    
            errors.rejectValue("jsonField", "notValid");
            
         }
    }
  • Related