Custom Json Validation in anypoint studio

884 Views Asked by At

I am trying to validate JSon using the json schema validator. But it returns a generic message. "Json content is not compliant with schema" . I have a HTTP POST REQUEST which sends a payload as follows:

{ "key1" : "value1", "key2" : "value2" ,"key3": "value3" }

if key1 and key2 is missing . I want it to give error messages as follows:

{{
  errorCode :1001,
  errorMessage : key1 is missing",
},
  errorCode :1002,
  errorMessage : key2 is missing"
}
}

I tried writing the errors to a file(json file containing all the warnings and messages} looks something like this:

{
  "level" : "error",
  "domain" : "validation",
  "keyword" : "required",
  "message" : "object has missing required properties ([\"key1\",\"key2\",\"key3\"])",
  "required" : [ "key1", "key2", "key3"],
  "missing" : [ "key1", "key2"]
}

This is just a small part of this file. I'll have to loop through the file to reach this information. Is there any other way , I can perform custom validations and return proper error messages to the user.

EDIT 1:

I have created the following RequestObj class:

public class RequestObj {

@Valid
@NotBlank
@NotNull
private String key1;

@Valid
@NotBlank
private String key2;

@Valid
@NotBlank
private String key3;

@Override
public String toString() {
    return "RequestObj [key1=" + key1 + ", key2=" + key2 + ", key3=" + key3 + "]";
}

enter image description here

It is not validating key1 as not null.

postman request :

POST /validate HTTP/1.1 Host: localhost:8081 Content-Type: application/json

{ "key2" :"gg", "key3" : "hh" }

EDIT 2: enter image description here

when I implement the validator interface. I dont get access to the mule Event. How will I access the json that I need to validate in this case ?

2

There are 2 best solutions below

0
HMT On BEST ANSWER

enter image description here

This is how my result looks after performing custom validations on the json input. I used JSR-303 annotations for validating the data.

class Example{ 
   @NotBlank
        @Size(min = 3, max = 5)
        private String key1;

        @Pattern(regexp=".+@.+\\.[a-z]+") // email
        private String key2;

        private String key3;
}

then I wrote a custom validator and I invoked the static function validate by passing all the values:

public class ValidationServiceImpl {

    public static HashMap<String,String> validate(String key1 , String key2 , String key3)  {
        HashMap<String,String> result = new HashMap();
        Example req = new Example(key1 , key2, key3);
    Validator validator;
    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    validator = validatorFactory.getValidator();
    Set<ConstraintViolation<Example>> violations = validator.validate(req);
    if(!CollectionUtils.isEmpty(violations)) {
        for (ConstraintViolation<Example> violation : violations) 
        {
            String propertyPath = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            result.put(propertyPath, message);
        }
    }
    return result;
    }

}

The result is the hashmap which returns all the violations.Logging it will give you the result.

POM dependencies required are:

<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.0.Final</version>
</dependency>
   <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator-annotation-processor -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator-annotation-processor</artifactId>
    <version>6.1.0.Final</version>
</dependency>


    <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.el/javax.el-api -->
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish/javax.el -->
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <version>3.0.0</version>
</dependency>
9
aled On

If the built-in JSON validator doesn't provide the validation or error reporting that you need, then you have to implement your own custom validator in Java. See the docs on how to implement a custom validator by extending the Validator interface and in your implementation class you can use any Java library to validate JSON, like for example Jackson or GSON. Then you can customize the error handling.