[英]HashMap to JSON response in Jersey 2
我的代码:
@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)
返回HashMap<String, String>
当我尝试返回APPLICATION_JSON
时咳嗽,我明白了
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.HashMap, genericType=class java.util.HashMap.
最简单的方法是什么? 谢谢
如果要将Jackson用作JSON提供程序 ,则将此依赖项添加到pom.xml应该足够了:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.2</version>
</dependency>
要查找其他选项,请参阅: https : //jersey.java.net/documentation/latest/media.html
我所知道的最简单的方法是使用ObjectMapper,并将映射传递给它的writeValueAsString()方法。 例如:
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);
返回的字符串是“{”2“:”two“,”1“:”one“}”。
Jersey内部包含String类型的实体提供程序,因此这应该可行。
编写自己的MessageBodyWritter以更好地适应更多用例并简化流程会更好。 你可以在这里找到文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.