简体   繁体   English

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

[英]java - how to parse two parameters on REST Web Service?

I'm trying to parse two arguments on a RESTful Web Service : a simple object and a List of another one. 我试图解析RESTful Web服务上的两个参数:一个简单的对象和另一个参数的List I'm working with the libraries jersey-bundle-1.19.1.jar and gson-2.4.jar . 我正在使用jersey-bundle-1.19.1.jargson-2.4.jar The application captures well the first, but the second is always null . 该应用程序很好地捕获了第一个,但第二个始终为null

Here is the code of the resource: 这是资源的代码:

/* 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);
    }
}

And this is the json i'm trying to parse on this method: 这是我正在尝试使用此方法解析的json:

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

Do I have some syntax error in the json structure? json结构中是否存在语法错误? Thanks. 谢谢。

You need to write a wrapper class ( dto ) that contains a reference of Compra and list of references of DetalleCompra , eg: 你需要写一个包装类( dto包含的参考) Compra的引用和列表DetalleCompra ,如:

public class Request {

    private Compra compra;

    private List<DetalleCompra> detalle;

    //Getters and setters
}

You can then change the putJson method to the follwing: 然后,您可以将putJson方法更改为putJson方法:

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

Also, your json seems to be invalid (verify here ), it should look something like this: 另外,您的json似乎无效(请在此处验证),它看起来应该像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM