0

I'm trying to develop a Jax-RS POST resource, reported here below:

@Path("testJson")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response testJson(Float firstValue, Float secondValue, String thirdValue) {

    LOG.info(" firstValue: " + firstValue);
    LOG.info(" secondValue: " + secondValue);
    LOG.info(" thirdValue: " + thirdValue);

    return Response.ok().build();
}

However, i get the following error:

 RESTEASY002305: Failed executing POST /aliments/testJson: org.jboss.resteasy.spi.ReaderException: javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error

Searching around, I understood that for a POST method that accepts a JSON, you need to give to it only one parameter, which is in fact the entire JSON message.

My questions are:

  1. Why can't I put two or more parameters? Is that because the Json represents the body part of the message and I can have only one body? Can you explain it better to me please?
  2. I can create a DTO that contains my parameters and use this DTO as one and only parameter for my POST method, but is this the best practice? Doing so, I will have a DTO for each POST method, which actually acts as a Wrapper.
  3. Is there anything I'm missing?

Thank you a lot for your time, Have a nice day.

PyroSandro
  • 35
  • 7

1 Answers1

0

Why can't I put two or more parameters? Is that because the Json represents the body part of the message and I can have only one body? Can you explain it better to me please?

JAX-RS allows for one "entity" parameter. This parameter represents the entire request entity. It is determined to be the entity parameter by not having any annotations1. If you want the raw entity, you can use an InputStream parameter. If you want a POJO, you can do so. How the conversion works is with the use of MessageBodyReaders. The reader will be chosen based on the Content-Type header and the parameter type. The framwork comes with some standard readers for easiliy convertable types. For example String, InputStream, byte[]. The reader will get passed the entity stream and it will need to convert the stream to the parameter type. You can read more about "Entity Providers" here.

If you want to use a common media type like JSON, there are libraries that handle JSON/POJO conversion, and from that library, a reader can be made. For JSON, a common librabry is Jackson, and there is a Jackson MessageBodyReader that is provided by the Jackson team.

I can create a DTO that contains my parameters and use this DTO as one and only parameter for my POST method, but is this the best practice? Doing so, I will have a DTO for each POST method, which actually acts as a Wrapper.

Yes, this is very common practice. Get used to it with these type of frameworks.

Is there anything I'm missing?

I don't know, you tell me.


1. Some special annotation are allowed like @Valid for bean validation.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720