我正在测试 Jersey,我想模拟一个生成此 JSON 对象的模拟端点
{
"Flight1" : 757,
"Flight2" : 107,
"Flight3" : 637,
}
所以我写了这个资源:
@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Flight 1", 765);
map.put("Flight 2", 657);
map.put("Flight 3", 908);
return map.toString();
}
但是当我调用/myjson 时我得到了这个响应
{ Flight 1=765, Flight 2=657, Flight 3=908 }
Jersey 已经知道哪个元素是字符串,哪个元素是整数,但它随后将其格式化为就好像它们都是数字一样。 此外,目前的 Json 不能被“漂亮”的格式化程序格式化,我相信这会使 http 客户端解析起来很困难。
所以我的问题是:
为什么会这样?
如何避免它并编写简单的模拟 JSON 对象以进行格式正确的测试
最佳答案
可以添加Jaxb注解,直接对响应对象进行序列化和反序列化,无需转换。为此,您需要添加 jersey 的 jaxb 库,以便在启动 jersey 环境时,它可以启用自动转换功能。
例子:
@Path("jaxbResource")
@Produces("application/xml")
@Consumes("application/xml")
public class UserResource {
@GET
public User[] getUserArray() {
List<User> userList = new ArrayList<User>();
userList.add(new User(1, "John"));
………
return userList.toArray(new User[userList.size()]);
}
}
@XmlRootElement
public class User {
private int id;
private String name;
public User() {}
public User(int id,String name) {
this.id = id;
this.name = name;
}
………
}
希望这有帮助!!!
关于java - 为什么这个 HashMap 在 Jersey/Tomcat 中的格式不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678140/