Q:

Pass json object to a play-framework action

I am currently using Play v1.2.3.  I have an endpoint to which I want to send a json object which will be deserialized into a Java object.  So, I have something that looks like this:
public class UserController extends Controller {

  public static class FullName {
    public String first;
    public String last;
  }

  public static void putName( FullName name ) { ... }
}

##### routes
PUT /user/name    UserController.putName

With that in place, I would hope to call the endpoint with the given javascript:
$.ajax({
  type: "PUT",
  data: { first: "Michael", last: "Bailey" },
  url: "/user/name"
});

Unfortunately, with the above setup, it seems that play is not wanting to send the entire data object, but is instead attempting to populate two parameters (first and last).  Is there a way to define the endpoint to consume the complete body directly, or does it have to be done by hand?

A:

To cast the entire input body into a Model class:
public static void create(JsonObject body) {
    CaseFolder caseFolder = new Gson().fromJson(body, CaseFolder.class);
    caseFolder.user = getConnectedUser();

    if(caseFolder.validateAndSave()) {
        renderJSON(
                new JSONSerializer()
                    .exclude("*.class")
                    .exclude("user")
                    .serialize(caseFolder));
    } else 
        error();
}

Also, the above code takes the resulting Model object and serializes it back out to JSON as the response body.
If you want to just access certain fields within the JSON request, you can use:
public static void update(JsonObject body) {
    try {
        Long id = (long) body.get("id").getAsInt();
        CaseFolder cf  = CaseFolder.loadAndVerifyOwner(getConnectedUser(), id);
        cf.number = body.get("number").getAsString();
        cf.description = body.get("description").getAsString();
        if(cf.validateAndSave())
            ok();
        else
            error();
    }
    catch (NullIdException      e) {error();} 
    catch (NotFoundException    e) {notFound();} 
    catch (NotOwnerException    e) {forbidden();}
    catch (Exception            e) {e.printStackTrace(); error();}
}

