【问题标题】:java - how to parse two parameters on REST Web Service?java - 如何解析 REST Web 服务上的两个参数?
【发布时间】:2017-02-05 21:38:33
【问题描述】:

我正在尝试解析 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 结构中有一些语法错误吗?谢谢。

【问题讨论】:

    标签: java json rest service jersey


    【解决方案1】:

    您需要编写一个包装类 (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"
        }]
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多