I'm trying to consume a JSON array I created using JavaScript but the array is never bound in my controller
Here is the JavaScript code I use to call my controller action
$.post("/produits_ajax",{filterParams:[{name:"milk", value:"chevre"}, {name:"pate", value:"molle"}]},
function(data){
$('.dynamicContent').html(data);
slideProducts();
// initialize scrollable
$(".scrollable").scrollable();
});
My routes file entry
POST /produits_ajax Application.produitsAjax
Here is how I receive it in my play! controller. I'm using play 1.1 and the JsonArray is from com.google.gson.JsonArray
public static void produitsAjax(JsonArray filterParams) {
if(filterParams != null)
Logger.debug("Le Json: " + filterParams.toString());
else
Logger.debug("filterParams is null");
render();
}
As you can imagine I always get "filterParams is null" in my console (I wouldn't be writhing this if I wasn't)
It's very basic so far I just want to bind the array generated in JS to my JsonArray. Play!framework has a great documentation but for some reason there is very little on this particular subject.
If anyone can shed some light on this It would be much appreciated
The Play JSON library. The play. api. libs. json package contains data structures for representing JSON data and utilities for converting between these data structures and other data representations.
You use the JSValue class to convert basic values, such as numbers and strings, between JavaScript and Objective-C or Swift representations to pass data between native code and JavaScript code.
JavaScript provides methods: JSON. stringify to convert objects into JSON.
You just have to create a TypeBinder class to add JsonObject binding capacity to Play!. Actually, that's pretty easy to achieve in Play 1.2. Here's the complete class:
@Global
public class JsonObjectBinder implements TypeBinder<JsonObject> {
@Override
public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception {
return new JsonParser().parse(value);
}
}
That's it! With the @Global annotation, Play will find it at load time and register this with the other binders. I use this in my controller with the following signature :
public static void handleJsonBody(JsonObject body) {
...
}
The body will be automatically parsed by Play. You can do the same for JsonArray to support your particular case.
You have 2 options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With