Bind a list of complex elements in the AJAX POST game structure

I have a simple Foo class with two attributes and a form binder:

 import play.data.Form; public class Foo { public static Form<Foo> form = Form.form(Foo.class); public String name; public List<Bar> bars = new ArrayList<Bar>(); } 

Where is the Bar class:

 public class Bar { public String prop1; public String prop2; } 

When I try to execute an ajax POST request:

 jsRoutes.controllers.Test.duh().ajax({ data: { name: "Test", bars: [{prop1: "first"}] } }); 

in the duh method, in the line:

 Form<Foo> request = Foo.form.bindFromRequest(); 

I get an error:

[InvalidPropertyException: Invalid property] [0] [prop1] 'from beanclass [models.Foo]: the property referenced by the path of the indexed property' bars [0] [prop1] 'is neither an array, nor a list, nor a map; the returned value was [first]]

AJAX form request Form data is as follows:

 name:Test bars[0][prop1]:first 

Question:. How can I link a list of complex elements in a gaming environment? What else is needed for this code to work?

+6
source share
2 answers

As mentioned in @fjtorres, the problem is with how jQuery.param serializes data. Play expects bars[0].prop1 instead of bars[0][prop1] . To work around this problem, I changed the code to the following:

interface:

 jsRoutes.controllers.Test.duh().ajax({ data: JSON.stringify({ name: "Test", bars: [{prop1: "first"}] }), headers: { "Content-Type": "application/json" } }); 

backend - controler: duh method:

 Form<Foo> request = Foo.form.bind(request().body().asJson()); 

This sends the data to the backend as JSON. The JsonNode JsonNode is retrieved from the request body and passed to the bind form.

0
source

According to the playframework clause in this URL (the POJO object binding section), the binding for the entity list should be bars [0]. prop1

0
source

Source: https://habr.com/ru/post/953617/


All Articles