Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey/JAX-RS: Return a Map as XML/JSON

Tags:

It's not so obvious how to return a Map as an XML/JSON document using the Jersey/JAX-RS framework. It already has support for Lists, but when it comes to Maps, there is no MessageBodyWriter. And even if I were to embed the Ma into a wrapper class, there is no map type in XML schema.

Any practical advice on how to marshal a Map into an XML/JSON document in Jersey?

like image 921
ktm5124 Avatar asked Sep 20 '13 21:09

ktm5124


People also ask

What can a JAX-RS method return?

If the URI path template variable cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 400 (“Bad Request”) error to the client. If the @PathParam annotation cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 404 (“Not Found”) error to the client.

Is Jax and Jersey RS the same?

JAX-RS is an specification (just a definition) and Jersey is a JAX-RS implementation. Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development.


1 Answers

I know its very late to reply, but I'm hoping it will help somebody someday :) The easiest and quickest fix I applied is

@GET
@Path("/{messageId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getMessage(@PathParam("messageId") long id) {
    Map<String, String> map = new HashMap<>();
    map.put("1", "abc");
    map.put("2", "def");
    map.put("3", "ghi");

    return Response.status(Status.OK).entity(map).build();
}

Output: { "1": "abc", "2": "def", "3": "ghi" }

This should definitely help you solve your trouble.

like image 192
NoisyBoy Avatar answered Oct 31 '22 02:10

NoisyBoy