使用 JAX-RS 将 JSON 查询参数转换为对象 [英] Convert JSON query parameters to objects with JAX-RS
问题描述
我有一个 JAX-RS 资源,它以这样的 JSON 字符串获取其参数:
I have a JAX-RS resource, which gets its paramaters as a JSON string like this:
http://some.test/aresource?query={"paramA":"value1", "paramB":"value2"}
在这里使用 JSON 的原因是查询对象在实际用例中可能非常复杂.
The reason to use JSON here, is that the query object can be quite complex in real use cases.
我想将 JSON 字符串转换为 Java 对象,在示例中为 dto:
I'd like to convert the JSON string to a Java object, dto in the example:
@GET
@Produces("text/plain")
public String getIt(@QueryParam("query") DataTransferObject dto ) {
...
}
JAX-RS 是否支持从作为查询参数传递的 JSON 到 Java 对象的这种转换?
Does JAX-RS support such a conversion from JSON passed as a query param to Java objects?
推荐答案
是的,您可以这样做,但您需要自己编写转换代码.幸运的是,这很容易,您只需要编写一个具有公共 String
构造函数的类来进行转换.例如:
Yes, you can do this, but you will need to write the conversion code yourself. Fortunately, this is easy, you just need to write a class that has a public String
constructor to do the conversion. For example:
public class JSONParam {
private DataTransferObject dto;
public JSONParam(String json) throws WebApplicationException {
try {
// convert json string DataTransferObject and set dto
}
catch (JSONException e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
.entity("Couldn't parse JSON string: " + e.getMessage())
.build());
}
}
public DataTransferObject getDTO() {
return dto;
}
}
然后你可以使用:
@GET
@Produces("text/plain")
public String getIt(@QueryParam("query") JSONParam json) {
DataTransferObject dto = json.getDTO();
...
}
这篇关于使用 JAX-RS 将 JSON 查询参数转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!