简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM