Wes
Wes

Reputation: 1259

HashMap to JSON response in Jersey 2

My Code:

@Path("/pac")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Component
    public class LDAPResource {
        @Autowired
        private LDAP_PAC_Service pacService;

        @GET
        @Path("/query/{userID}")
        public Response getPAC(@PathParam("userID") String userID) {
            return Response.ok().entity(pacService.getPAC(userID)).build();
        }
    }

pacService.getPAC(userID) returns a HashMap<String, String>

It coughs when I try to return APPLICATION_JSON, I get

SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.HashMap, genericType=class java.util.HashMap.

What's the easiest way to accomplish this? Thanks

Upvotes: 1

Views: 2128

Answers (2)

whoisdan
whoisdan

Reputation: 86

The easiest way I'm aware of is to use ObjectMapper, and pass in the map to its writeValueAsString() method. For example:

import com.fasterxml.jackson.databind.ObjectMapper;

    Map<String, String> mapData = new HashMap<>();
    mapData.put("1", "one");
    mapData.put("2", "two");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValueAsString(mapData);

The string returned is "{"2":"two","1":"one"}".

Jersey internally contains entity providers for String type so this should work.

It'd be better to write your own MessageBodyWritter to accommodate more use cases and streamline the process. You can find the documentation here

Upvotes: 1

Meiko Rachimow
Meiko Rachimow

Reputation: 4724

If you want to use Jackson as your JSON provider, adding this dependency to your pom.xml should be enough:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.22.2</version>
</dependency>

To find other options, see: https://jersey.java.net/documentation/latest/media.html

Upvotes: 2

Related Questions