java - 如何在REST Web服务上解析两个参数?

时间:2017-02-05 21:38:34

标签: java json rest service jersey

我试图在 RESTful Web服务上解析两个参数:一个简单的对象和另一个的List。我正在使用图书馆jersey-bundle-1.19.1.jargson-2.4.jar。应用程序首先捕获的很好,但第二个应用程序始终是null

以下是资源的代码:

/* Package and imports*/

@Path("compra")
public class CompraResource {

    @Context
    private UriInfo context;
    // Class with connection to database, works well
    private final CompraService service;
    private final Gson json;

    /**
     * Creates a new instance of CompraResource
     */
    public CompraResource() {
        this.service = new CompraService();
        this.json = new GsonBuilder().setDateFormat(Metodos.Parametros.FECHA_FORMATO).create();
    }

    /**
     * PUT method for updating or creating an instance of CompraResource
     * @param compra
     * @param detalle
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Path("registro")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String putJson(Compra compra, List<DetalleCompra> detalle) {
        return this.json.toJson(this.service.registrarCompra(compra, detalle), Boolean.class);
    }
}

这是json我试图解析这个方法:

{
    "id":"0",
    "fecha":"2017-01-20",
    "total":"0",
    "usuario":"jjuarezo"
},
[
    {
        "id":"0",
        "cantidad":"2",
        "idArticulo":"1",
        "idCompra":"0"
    }
]

我在json结构中有一些语法错误吗?感谢。

1 个答案:

答案 0 :(得分:0)

您需要编写一个包装类(dto),其中包含Compra的引用和DetalleCompra的引用列表,例如:

public class Request {

    private Compra compra;

    private List<DetalleCompra> detalle;

    //Getters and setters
}

然后,您可以将putJson方法更改为以下内容:

public String putJson(Request request) {
//Call getCompra and getDetalle to access the members

此外,您的json似乎无效(验证here),它应该如下所示:

{
    "compra": {
        "id": "0",
        "fecha": "2017-01-20",
        "total": "0",
        "usuario": "jjuarezo"
    },
    "detalle": [{
        "id": "0",
        "cantidad": "2",
        "idArticulo": "1",
        "idCompra": "0"
    }]
}