For this recipe, we will explore how Play Framework allow us to receive JSON objects easily and enable us to automatically convert them into model instances.
For Java, we need to take the following steps:
Run the
foo_java
application with Hot-Reloading enabled.Modify the products controller in
foo_java/app/controllers/Products.java
by adding our product creation action:@BodyParser.Of(BodyParser.Json.class) public static Result postProduct() { JsonNode json = request().body().asJson(); String sku = json.findPath("sku").textValue(); String title = json.findPath("title").textValue(); Product p = new Product(); p.sku = sku; p.title = title; Product.add(p); return created(Json.toJson(p)); }
We need to add the following import statement for Play's JSON libraries:
import com.fasterxml.jackson.databind.JsonNode;
Add a new route for the product listing action in
foo_java/conf/routes
:POST /products controllers.Products.postProduct...