Deserialize post/get params with Sitebricks

654 Views Asked by At

In sitebricks, I can easily deserialize a class from params in json format in Sitebricks @Service method like this:

request.read(Person.class).as(Json.class); 

But how do I deserialize a class from get/post params?

I know the Request object has access to the params (request.params()) but it would require more effort.

2

There are 2 best solutions below

0
On BEST ANSWER

If the object that I want deserialize is not the service itself, then I would have to inject Json to do the deserialization.

public class TestPage {
   @Inject Json json;

   @Post
   public void post(Request request) {
     String data = request.param("data");
     Person p = json.in(new ByteArrayInputStream(data.getBytes()), Person.class);

     ...
   }
}
1
On

In your module declare your handler class :

at("/test").serve(TestPage.class); 

Then declare your TestPage with members and associate getters/setters corresponding to your get/post params

public class TestPage {

    private String param;

    @Get
    public Reply<?> get() {
        // request get param "param" is already mapped in param
    }

    @Post
    public Reply<?> post() {
        // request post param "param" is already mapped in param
    }


    public void setParam(String param) {
        this.param = param;         
    }

    public String getParam() {
        return this.param;
    }        

}

Then call your url /test with get or post parameter "param".

Check out http://sitebricks.org/#requestandreply

Hope that helps.

Rgds