Wednesday, 21 September 2016

Input Json Model Validation using Jackson and Gson

      

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.gson.JsonIOException;

public class JsonValidator {
 
 
 public static void main(String[] args) throws JsonIOException, IOException {
  
  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
         Validator validator = factory.getValidator();
         ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
         List jsonObjString = new ArrayList();
         jsonObjString.add("postBox: Mumbai " );
        
         for(String attribute  : jsonObjString){
             System.out.println("Attribute :\n" + attribute);
             Address user = null;
             try {
                 user = objectMapper.readValue(attribute, Address.class);
             } catch (IOException e) {
               System.out.println("Exception caught:");
             }
             if (user != null) {
                 final Set> violations = validator.validate(user);
                 if (violations.size() > 0) {
                     System.out.println("Config contains errors:");
                     for (ConstraintViolation
u : violations){ System.out.println(" \"" + u.getPropertyPath().toString() + "\"" + " " + u.getMessage()); } } else { System.out.println("NO ERRORS " ); } } }; } } /// ADD a model class of Address to test the validation and the messages returned for the import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonInclude; import com.sun.istack.internal.NotNull; /** * Author : Sanal Samuel * */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Address { @NotNull @NotEmpty(message="Incorrect Data") private String postBox; @NotNull @NotEmpty(message="Incorrect Data") private String flatNumber; public String getPostBox() { return postBox; } public void setPostBox(String postBox) { this.postBox = postBox; } public String getFlatNumber() { return flatNumber; } public void setFlatNumber(String flatNumber) { this.flatNumber = flatNumber; } }

No comments:

Post a Comment

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...