HashMap 到 Jersey 2 中的 JSON 响应
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)
return一个HashMap<String, String>
当我尝试 return APPLICATION_JSON
时它咳嗽,我得到
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.HashMap, genericType=class java.util.HashMap.
完成此操作的最简单方法是什么?谢谢
如果您想使用 Jackson as your JSON provider,将此依赖项添加到您的 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 以容纳更多用例并简化流程。您可以找到文档 here
我的代码:
@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)
return一个HashMap<String, String>
当我尝试 return APPLICATION_JSON
时它咳嗽,我得到
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.HashMap, genericType=class java.util.HashMap.
完成此操作的最简单方法是什么?谢谢
如果您想使用 Jackson as your JSON provider,将此依赖项添加到您的 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 以容纳更多用例并简化流程。您可以找到文档 here