使用JAX-RS将JSON查询参数转换为对象 [英] Convert JSON query parameters to objects with JAX-RS

查看:232
本文介绍了使用JAX-RS将JSON查询参数转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆