JSON consumption in the game! structure controller

I am trying to use a JSON array created using JavaScript, but the array is never bound in my controller

Here is the JavaScript code that I use to call my action with the controller

$.post("/produits_ajax",{filterParams:[{name:"milk", value:"chevre"}, {name:"pate", value:"molle"}]}, function(data){ $('.dynamicContent').html(data); slideProducts(); // initialize scrollable $(".scrollable").scrollable(); }); 

Entrance to my route

 POST /produits_ajax Application.produitsAjax 

This is how I get it in my game! controller. I am using play 1.1 and 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 feed it if I hadn’t)

It is very simple so far I just want to associate the array generated in JS with my JsonArray. Play! The Framework has excellent documentation, but for some reason there is very little on this.

If anyone can shed light on this, it would be very appreciated

+6
source share
2 answers

You just need to create a TypeBinder class to add the ability to bind JsonObject to Play !. This is actually pretty easy to achieve in Play 1.2. Here's the full 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); } } 

What is it! Using the annotation, @Global Play will find it at boot time and register it using other binders. I use this in my controller with the following signature:

 public static void handleJsonBody(JsonObject body) { ... } 

The body will be automatically analyzed on Play. You can do the same for JsonArray to support your specific case.

+17
source

You have 2 options:

  • simple: pass the parameter as a String and in the controller parse it into Json
  • complicated: create your own binder using TypeBinder
+4
source

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


All Articles