JSON validation solution

Hi,

I am using Play to build a pure REST API application that produces and consumes JSON. Does Play come with anyway to validate JSON input similar to Form validation? For example, if I have a POST endpoint that takes a JSON object, is there anyway for me to annotate a Java POJO (which represents the incoming JSON, converted by the Bodyparser) to say a field cannot be null or empty?

Thanks

3 Likes

Does Play come with anyway to validate JSON input similar to Form validation? For example, if I have a POST endpoint that takes a JSON object

I have recently had a similar challenge.

Play’s form can be used with JSON, but it is brittle. Because the internal representation used is Map[String, String]. So, there are a few problems with counter-intuitive behaviours that come with it: https://github.com/GIVESocialMovement/play-json-form#important-compatibility-notes

@chrono_b Have used Hibernate Bean validator to annotate POJOs obtained from the incoming JSON.
Works pretty well with Play 2.x

e.g :

public class TestCampaign {

    @JsonProperty("name")
    @NotNull(groups = DisplayLineChecks.class)
    @Size(min = 1, max = 20, message = "Display line cannot be empty and cannot exceed 20 characters")
    private String name;

    @JsonProperty(value = "state")
    @DomainValues(values = {"draft", "rejected", "accepted"}, message = "Value %s not present in allowed values [draft, rejected, accepted] list")
    private String disposition = "draft";

    @JsonProperty("tags")
    private String tags;

    @JsonProperty("campaignName")
    @NotNull
    private String campaignName;

    @NotNull
    @DomainValues(values = {"simple", "percent"}, message = "Value %s not present in allowed values [simple, percent] list")
    private String discountType;

  
    @JsonProperty(value = "currency")
    @Pattern(regexp = "[a-zA-Z]{3}", message = "Invalid value %s")
    private String currency;
 
...
}