Nick
Nick

Reputation: 2980

Inject complex object into resource method in Jersey

I'm working on a RESTful service in Java 8. I have the following method in my resource class, which responds to POST requests.

@POST
public Response store(SomeType myInstance){ ... }

Typically, this get's deserialised without a hitch in case the json request can be directly mapped. However, SomeType in this case is a complex object containing other objects persisted in a database.

Is there a way to capture the request, figure out the type, build the object SomeType and then pass it through to the store method? I'm leaning towards some type of middleware, yet I'm not quite sure how the dependencies would work.

Note: For security reasons, I am very limited in 3rd party packages that I can use. So I can't use out of the box solutions.

Upvotes: 0

Views: 48

Answers (1)

ilooner
ilooner

Reputation: 2560

I think your use case can be solved with Jackson's CustomDeserializer feature.

  1. The general approach would be to create a class for each incoming type you need to support. Ex. SomeType1, SomeType2, SomeType3`.
  2. All of these classes should extend the SomeType parent class.
  3. The SomeType parent class should have a CustomDeserializer.
  4. In the CustomDeserializer you can inspect the json fields to determine what type the json should be deserialized to.
  5. Then you can use the JsonParser.readValueAs method to deserialize the json into the desired type SomeType1, SomeType2, or SomeType3.
  6. If you need to fetch some more data from a database and populate fields of SomeType1, SomeType2, and SomeType3 you can do that within your handler by checking the object type.

    @POST
    public Response store(SomeType myInstance) {
       if (myInstance instanceof SomeType1) {
         // fetch from database and populate more fields
       } else if (myInstance instanceof SomeType2) {
         ...
       }
       ...
    }
    

Upvotes: 1

Related Questions