简体   繁体   English

泽西2中的HashMap到JSON响应

[英]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> pacService.getPAC(userID)返回HashMap<String, String>

It coughs when I try to return APPLICATION_JSON , I get 当我尝试返回APPLICATION_JSON时咳嗽,我明白了

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: 如果要将Jackson用作JSON提供程序 ,则将此依赖项添加到pom.xml应该足够了:

<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 要查找其他选项,请参阅: 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. 我所知道的最简单的方法是使用ObjectMapper,并将映射传递给它的writeValueAsString()方法。 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"}". 返回的字符串是“{”2“:”two“,”1“:”one“}”。

Jersey internally contains entity providers for String type so this should work. Jersey内部包含String类型的实体提供程序,因此这应该可行。

It'd be better to write your own MessageBodyWritter to accommodate more use cases and streamline the process. 编写自己的MessageBodyWritter以更好地适应更多用例并简化流程会更好。 You can find the documentation here 你可以在这里找到文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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