0

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.

Glide
  • 20,235
  • 26
  • 86
  • 135

2 Answers2

3

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

Thomas
  • 1,410
  • 10
  • 24
  • Your solution definitely works if the object to deserialize is the @Service (request entry-point) itself. I was looking for a solution that works when the object and the service class are two different classes. – Glide Sep 27 '12 at 01:13
3

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);

     ...
   }
}
Glide
  • 20,235
  • 26
  • 86
  • 135