我的资源类中有以下用于Java REST服务的方法。

@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Player createCustomer(Customer customer)
{
    System.out.println("Request for Create");

    System.out.println(""+customer.getID()+"\n"+customer.getTableID()+"\n"+customer.getCustNick());

    //Above statement should print the details I send via JSON object

    //return custdao.create(customer); //Want to call this to add new "customer"  into database table.

    return player;
}


在填写表单中的输入字段并单击创建按钮后,我将按照jQuery方法进行调用。

function createEntry() {
        var formData = JSON.stringify({
            "ID" : $("input[name='txtID']").val(),
            "tableID" : $("input[name='txtTableID']").val(),
            "custNick" : $("input[name='txtNick']").val()
        });

        console.log(formData); //Just to see if form details are JSON encoded.

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: baseURL,
            dataType: "json",
            data: formData,
            success: function(data) {
                console.log("Customer Added!");
                $("div.response").append("<h3>New Customer ("+ $("input[name='txtNick']").val() +") Added on the Server</h3>");
            }
        });
    }


但是在服务器上,我得到的是空的“客户”对象,我在这里做错了什么?如果您需要任何其他详细信息(关于客户类别模型),请告诉我。

更新:以下是客户类。

/*ignore imports, all required imports are included */

@XmlRootElement
public class Customer
{
    private int id;
    private int tableid;
    private String custnick;

    public int getID()
    {
            return id;
    }

    public void setID(int id)
    {
            this.id = id;
    }

    ....
    ....
    /* Similar Setter-Getter Methods for the fields */
}


我认为问题与“客户”类的XML模式有关,并且我在JSON对象中发送的节点名称与模式不匹配,这就是为什么它可能无法使用模型类的setter方法映射字段的原因当然可以。

最佳答案

该问题可能是由字段名称不匹配引起的。

您可以在实体类上使用@XmlElement JAXB批注设置字段所需的任何名称,以使其变得清晰。只需点击以下链接:http://jaxb.java.net/tutorial/section_6_2_7_1-Annotations-for-Fields.html#Annotations%20for%20Fields

10-01 21:16
查看更多