[英]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.