使用 JAX-RS 将 JSON 查询参数转换为对象

发布于 2024-08-30 11:43:42 字数 412 浏览 6 评论 0原文

我有一个 JAX-RS 资源,它以 JSON 字符串的形式获取其参数,如下所示:

http://some.test/aresource?query={"paramA":"value1", "paramB":"value2"}

此处使用 JSON 的原因是查询对象在实际用例中可能非常复杂。

我想将 JSON 字符串转换为 Java 对象,示例中为 dto:

@GET 
@Produces("text/plain")
public String getIt(@QueryParam("query") DataTransferObject dto ) {
    ...
}

JAX-RS 支持从作为查询参数传递的 JSON 到 Java 对象的这种转换吗?

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"}

The reason to use JSON here, is that the query object can be quite complex in real use cases.

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 ) {
    ...
}

Does JAX-RS support such a conversion from JSON passed as a query param to Java objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

话少情深 2024-09-06 11:43:42

是的,您可以这样做,但您需要自己编写转换代码。幸运的是,这很容易,您只需要编写一个具有公共 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;
    }
}

那么你可以使用:

@GET 
@Produces("text/plain")
public String getIt(@QueryParam("query") JSONParam json) {
    DataTransferObject dto = json.getDTO();
    ...
}

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;
    }
}

Then you can use:

@GET 
@Produces("text/plain")
public String getIt(@QueryParam("query") JSONParam json) {
    DataTransferObject dto = json.getDTO();
    ...
}
生生漫 2024-09-06 11:43:42

如前所述,您确实需要显式从 String 参数转换为 JSON。但没有必要使用像 org.json 的解析器这样原始的东西; JacksonGson a> 可以在一两行内进行数据绑定(字符串到 JSON、JSON 到 POJO)。使用 Jackson:(

MyValue value = new ObjectMapper().readValue(json, MyValue.class);

对于生产代码,只需创建一次 ObjectMapper 作为静态成员,即可重用)

Jackson 是大多数 JAX-RS 实现用来实现 POST 数据的数据绑定的工具,因此这非常相似。

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; Jackson or Gson can do data binding (String to JSON, JSON to POJO) in a line or two. With Jackson:

MyValue value = new ObjectMapper().readValue(json, MyValue.class);

(for production code, just create ObjectMapper once as static member, reuse)

Jackson is what most JAX-RS implementations use to implement data-binding for POST data, so this is quite similar.

浮云落日 2024-09-06 11:43:42

到 Jason 的解决方案(由 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;
    }                  
}

使用 http://www.json.org/java/添加 重新发明轮子:-)

Adding to Jason's solution, using http://www.json.org/java/ (courtesy of 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 :-)

娇纵 2024-09-06 11:43:42

JAX-RS 支持使用 JAXB(Java API for XML Binding)将 JavaBean 绑定到 XML 或 JSON,反之亦然。可以在此处找到更多详细信息,例如: http:// /www.ibm.com/developerworks/web/library/wa-aj-tomcat/index.html

您需要

  • 在 DataTransferObject 上添加 @XmlRootElement 注释
  • 在 DataTransferObject 中创建一个空的默认构造函数
  • 添加 @Consumes(MediaType.APPLICATION_JSON ) 对您的 WebService 进行注释

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

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
香橙ぽ 2024-09-06 11:43:42

如果您有兴趣生成 DTO,我可以建议 jsonschema2pojo 吗?您可以使用 JSON Schema 定义对象并自动生成 DTO。

编写架构后,您还可以将其提供给消费者,以便他们准确理解请求的格式。

If you're interested in generating your DTOs, can I suggest jsonschema2pojo? You can define your objects using JSON Schema and have your DTOs automatically generated.

Once you've written the schema, you can also give it to your consumers so that they understand exactly how requests should be formatted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文