简体   繁体   中英

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. I'm working with the libraries jersey-bundle-1.19.1.jar and gson-2.4.jar . The application captures well the first, but the second is always 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:

{
    "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? Thanks.

You need to write a wrapper class ( dto ) that contains a reference of Compra and list of references of DetalleCompra , eg:

public class Request {

    private Compra compra;

    private List<DetalleCompra> detalle;

    //Getters and setters
}

You can then change the putJson method to the follwing:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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