Java 使用 JAX-RS 将 JSON 查询参数转换为对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2697541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JSON query parameters to objects with JAX-RS
提问by deamon
I have a JAX-RS resource, which gets its paramaters as a JSON string like this:
我有一个 JAX-RS 资源,它将其参数作为 JSON 字符串获取,如下所示:
http://some.test/aresource?query={"paramA":"value1", "paramB":"value2"}
The reason to use JSON here, is that the query object can be quite complex in real use cases.
在这里使用 JSON 的原因是查询对象在实际用例中可能非常复杂。
I'd like to convert the JSON string to a Java object, dto in the example:
我想将 JSON 字符串转换为 Java 对象,在示例中为 dto:
@GET
@Produces("text/plain")
public String getIt(@QueryParam("query") DataTransferObject dto ) {
...
}
Does JAX-RS support such a conversion from JSON passed as a query param to Java objects?
JAX-RS 是否支持从作为查询参数传递的 JSON 到 Java 对象的这种转换?
采纳答案by Jason Day
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:
是的,您可以这样做,但您需要自己编写转换代码。幸运的是,这很容易,您只需要编写一个具有公共String
构造函数的类来进行转换。例如:
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;
}
}
Then you can use:
然后你可以使用:
@GET
@Produces("text/plain")
public String getIt(@QueryParam("query") JSONParam json) {
DataTransferObject dto = json.getDTO();
...
}
回答by Mike K
Adding to Jason's solution, using http://www.json.org/java/(courtesy of Crockford):
添加到 Jason 的解决方案中,使用http://www.json.org/java/(Crockford提供):
import org.json.JSONObject;
public class JSONParam {
private DataTransferObject dto;
public JSONParam(String json) throws WebApplicationException {
try {
// convert json string DataTransferObject and set dto
JSONObject jo = new JSONObject(json);
dto.setParamA(jo.getString("paramA"));
dto.setParamB(jo.getString("paramB"));
// There are other get methods for Integer, Double, etc.
// You can also build JSON from Java objects.
}
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;
}
}
Don't re-invent the wheel :-)
不要重新发明轮子:-)
回答by StaxMan
As mentioned, you do need to explicitly convert from String parameter to JSON. But there is no need to use something as primitive as org.json's parser; Hymansonor Gsoncan do data binding (String to JSON, JSON to POJO) in a line or two. With Hymanson:
如前所述,您确实需要将 String 参数显式转换为 JSON。但是没有必要使用像 org.json 的解析器那样原始的东西;Hymanson或Gson可以在一两行中进行数据绑定(字符串到 JSON,JSON 到 POJO)。与Hyman逊:
MyValue value = new ObjectMapper().readValue(json, MyValue.class);
(for production code, just create ObjectMapper once as static member, reuse)
(对于生产代码,只需创建一次 ObjectMapper 作为静态成员,重复使用)
Hymanson is what most JAX-RS implementations use to implement data-binding for POST data, so this is quite similar.
Hymanson 是大多数 JAX-RS 实现用来实现 POST 数据的数据绑定的工具,因此这非常相似。
回答by joelittlejohn
If you're interested in generating your DTOs, can I suggest jsonschema2pojo? You can define your objects using JSON Schemaand have your DTOs automatically generated.
如果您有兴趣生成 DTO,我可以建议jsonschema2pojo吗?您可以使用JSON Schema定义对象并自动生成 DTO。
Once you've written the schema, you can also give it to your consumers so that they understand exactly how requests should be formatted.
编写架构后,您还可以将其提供给您的使用者,以便他们准确了解应如何格式化请求。
回答by lili
JAX-RS supports the use of JAXB (Java API for XML Binding) to bind a JavaBean to XML or JSON and vise versa. More details can be found here, for example: http://www.ibm.com/developerworks/web/library/wa-aj-tomcat/index.html
JAX-RS 支持使用 JAXB(用于 XML 绑定的 Java API)将 JavaBean 绑定到 XML 或 JSON,反之亦然。可以在此处找到更多详细信息,例如:http: //www.ibm.com/developerworks/web/library/wa-aj-tomcat/index.html
You need to
你需要
- Add @XmlRootElement annotation on DataTransferObject
- Create it an empty default constructor in DataTransferObject
- Add @Consumes(MediaType.APPLICATION_JSON) annotation to your WebService
- 在 DataTransferObject 上添加 @XmlRootElement 注释
- 在 DataTransferObject 中创建一个空的默认构造函数
- 将 @Consumes(MediaType.APPLICATION_JSON) 注释添加到您的 WebService
回答by Yaroslav
Maybe you could use http://docs.spring.io/spring-framework/docs/2.5.x/api/org/springframework/beans/BeanUtils.html
也许你可以使用 http://docs.spring.io/spring-framework/docs/2.5.x/api/org/springframework/beans/BeanUtils.html
BeanUtils.copyProperties(source, target)