简体   繁体   English

AngularJS:使用$ http.post传递复杂的json数据

[英]AngularJS: passing complex json data using $http.post

I'm having trouble passing a complex json object in angularjs with $http.post. 我在使用$ http.post在angularjs中传递复杂的json对象时遇到麻烦。 I'm keep getting a 400 bad request error sent back from the server saying the request was syntactically incorrect. 我不断收到从服务器发回的400错误请求错误,说该请求在语法上是不正确的。 I believe it has something to do with the array since it passes fine when i don't include it. 我相信它与数组有关,因为当我不包含它时,它可以很好地通过。

json i'm passing. 我通过的json。

{
    customer: {
        firstName: "John",
        lastName: "Doe",
        street: "1234 South Dr",
        city: "Detroit",
        state: "MI",
        zip: "12345",
        phone: "123-321-1234",
        email: "EMAIL@GMAIL.COM"
    },
    order: {
        orderDate: "06-16-2015",
        registerNum: "1",
        transactionNum: "7820",
        deliveryStatusID: 1,
        notes: "Hold order until July",
        items: [
            {skuID: "1234568",
             skuDescription: "Order item 1",
             qty: "4",
             itemStatusID: 1,
             itemStatusDescription: "Backorder"
             },
            {skuID: "7387491",
             skuDescription: "Order item 2",
             qty: "1",
             itemStatusID: 1,
             itemStatusDescription: "Flagged"
            }
        ]
    }
}

angular service function 角度服务功能

this.addOrder = function(new_order) {
    return $http.post(base + "/add", new_order);
};

Spring MVC controller method Spring MVC控制器方法

@RequestMapping(value="/add", method=RequestMethod.POST)
public void addOrder(@RequestBody CustomerOrder customerOrder) {

    System.out.println("----CUSTOMER-INFO----");
    System.out.println(customerOrder.getCustomer().getFirstName());
    System.out.println(customerOrder.getCustomer().getLastName());

    System.out.println("");
    System.out.println("----ORDER-INFO----");
    System.out.println(customerOrder.getOrder().getOrderID());
    System.out.println(customerOrder.getOrder().getOrderDate());       

}

The problem only seems to occur when I pass the items array in the json. 仅当我在json中传递items数组时,才出现问题。 I've passed the same json object without the items array and it works fine. 我已经传递了没有项目数组的同一个json对象,并且工作正常。 The format of the json is being sent in the same format that gets returned whenever I GET an order with my angularjs service method so I'm really not sure as to where I'm going wrong with this. json的格式以与我每次使用angularjs服务方法获取订单时都会返回的格式相同的格式发送,因此我真的不确定我在哪里出错。

If I need to provide more code please let me know. 如果我需要提供更多代码,请告诉我。 I appreciate any effort in helping me out. 感谢您为我提供的帮助。

Thank you. 谢谢。

Jason 杰森

Well after struggling to find my error in this problem, I finally found a solution. 在努力找到这个问题的错误之后,我终于找到了解决方案。 I thought I'd share how I debugged and fix this problem in case someone else is in a similar situation as I was. 我以为我会分享如何调试和解决此问题,以防别人遇到与我相似的情况。

After trying every possible way of sending my data in angular to the server and continually getting the same HTTP 400 error, I decided to send the json as a string and accept the json as a string in my spring mvc controller like this. 在尝试了将数据以一定角度发送到服务器并不断出现相同的HTTP 400错误后,我决定像这样在我的spring mvc控制器中将json作为字符串发送并接受json作为字符串。

angular service method: 角度服务方法:

this.addOrder = function(new_order) {
    return $http.post(base + "/add", angular.toJson(new_order));
};

spring controller 弹簧控制器

@RequestMapping(value="/add", method=RequestMethod.POST, consumes="application/json")
public void addOrder(@RequestBody String json) {

}

From here I simply took the json passed in and used the Jackson ObjectMapper to convert the json string to my POJO like this. 从这里,我只是简单地接收传入的json,并使用Jackson ObjectMapper这样将json字符串转换为我的POJO。

mapping json string to pojo 将json字符串映射到pojo

@RequestMapping(value="/add", method=RequestMethod.POST, consumes="application/json")
public void addOrder(@RequestBody String json) {

    ObjectMapper mapper = new ObjectMapper();

    try {

        CustomerOrder order = mapper.readValue(json, CustomerOrder.class);
        System.out.println(order.getCustomer().getFirstName() + " " + order.getCustomer().getLastName());

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
}

After doing this and running my code, I would get an UnrecognizedPropertyException on a field in my Items class when trying to bind the items json to the List in my Order class. 完成此步骤并运行我的代码后,当尝试将Items json绑定到我的Order类中的List时,我的Items类中的字段上将收到UnrecognizedPropertyException。 It was just a simple mispelling on the json side and I completely missed it. 在json方面,这只是一个简单的拼写错误,我完全错过了它。 After correcting this, jackson mapped everything correctly and I no longer get this HTTP 400 Error The request was syntactically incorrect. 更正此错误后,杰克逊正确地映射了所有内容,并且我再也未收到此HTTP 400错误该请求在语法上不正确。

Another thing to note is that if you pass your object as a string in angular using the JSON.stringify you may encounter this same exception on hashKey field in the JSON object. 要注意的另一件事是,如果使用JSON.stringify将对象作为有角度的字符串传递,则在JSON对象的hashKey字段上可能会遇到相同的异常。 The hashKeys are used by angular to monitor changes. hashKey由angular使用,用于监视更改。 I believe you can use a jackson annotation to ignore unknown fields or you can simply use angular.toJson instead which will remove all the hasKey/values for you which is what I did. 我相信您可以使用jackson批注来忽略未知字段,或者可以简单地使用angular.toJson代替,这将为您删除所有hasKey / values,这正是我所做的。

Just formatted the Json in a better way. 只是以更好的方式格式化了Json。 Try this if it helps. 如果有帮助,请尝试此操作。 Also, post the java classes if possible: 另外,如果可能,发布java类:

{
    "customer": {
        "firstName": "John",
        "lastName": "Doe",
        "street": "1234 South Dr",
        "city": "Detroit",
        "state": "MI",
        "zip": "12345",
        "phone": "123-321-1234",
        "email": "EMAIL@GMAIL.COM"
    },
    "order": {
        "orderDate": "06-16-2015",
        "registerNum": "1",
        "transactionNum": "7820",
        "deliveryStatusID": 1,
        "notes": "Hold order until July",
        "items": [
            {
             "skuID": "1234568",
             "skuDescription": "Order item 1",
             "qty": "4",
             "itemStatusID": 1,
             "itemStatusDescription": "Backorder"
             },
            {
             "skuID": "7387491",
             "skuDescription": "Order item 2",
             "qty": "1",
             "itemStatusID": 1,
             "itemStatusDescription": "Flagged"
            }
        ]
    }
}

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

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