dinezhr
dinezhr

Reputation: 11

Generating a custom response from a pojo in JAX-RS

I have a requirement as follows.

Emp{
 String id;
 String name;
}

Employee emp = (Object from service)
builder.entity(emp);

but while building reponse as JSON, I would like to generate it as

{
 employee_id : val,
 full_name : val,
 //custom attribute in pojo i wanted to inject
 company_url : xxx.com
}

Here I dont have access for the Emp class to add the attribute to change the JSON element name using annotations.

Upvotes: 1

Views: 100

Answers (1)

Xavier Coulon
Xavier Coulon

Reputation: 1600

You could create an EmpDTO class annotated with JAXB annotations, instanciate that class in your Resource Method and return it (with all the extra data you need, as you explained), then the JAX-RS implementation would convert the DTO into a JSON message.

Or you could make your own MessageBodyWriter (annnotated with @Producer + @Produces("application/json")) and process the Emp class and produce a JSON message (using the JSON-P API for example).

HTH. Xavier

Upvotes: 1

Related Questions