2

I need to make object from Json in PlayFramework.

 Example example =  Json.fromJson( request().body().asJson() , Example.class);

But I need to always have all values in object.

class Example{
  @Required_from_Json public String name;
  @Required_from_Json public boolen dead;
  @Required_from_Json public Integer age;
   .
   .
 50 more values
}

If one of them in Json are missing, it still create object but with null value. I need to cause some exception (probably NullPointException) if some value is missing in json or if object is "null" And its silly to inspect each property separately (like age != null)

Have you guys any advice for that?

Thanks!!

Ravi Ranjan
  • 740
  • 2
  • 10
  • 31
TyZet
  • 61
  • 5

2 Answers2

0

This question is very similar to yours. It's not about play but still about jackson:

Configure Jackson to throw an exception when a field is missing

EDIT: You can create short validator by yourselves:

for (Field f : obj.getClass().getFields()) {
  f.setAccessible(true);
  if (f.get(obj) == null) {
     // Throw error or return "bad request" or whatever
  }
}

This example is based on the Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Community
  • 1
  • 1
Andriy Kuba
  • 8,093
  • 2
  • 29
  • 46
0

Since your JSON object is coming from the request, you could actually use Play's Form facility to handle your situation.

In your controller method you would simply call it as below:

final Form<Example> form = Form.form(Example.class).bindFromRequest();

to bind the data from the request. Then you can check to see if there are any errors like this:

    if(from.hasErrors()) {
        return badRequest(form.errorsAsJson());
    }

and retrieve the object from the form if no errors

    Example obj = form.get();

Your Example class would also need to changed to use Play's validation Contraints:

import play.data.validation.Constraints;
...

class Example{
  @Constraints.Required public String name;
  @Constraints.Required public boolean dead;
  @Constraints.Required public Integer age;
  .
  .
  50 more values
}

EDIT: I should note here that your JSON object property names and class property variable names have to be the same for the mapping to work automatically.

This way is pretty nice as the errors that it returns are field specific so you can display them to your users and it will return all the error for all the fields in one json object (form.errorsAsJson()). You also have the added benefit of using the other validation annotations provided by Play (e.g. @Contraints.Email,@Constraints.MinLenth etc.)

Note that this worked for me on Play 2.3.x. I haven't use any recent version of play so YMMV.

jsonmurphy
  • 1,600
  • 1
  • 11
  • 19