我有以下代码用于ShipEngine API。 API需要JSON数组。我以为我有正确的Swift语法,但是我得到一个错误结果,表明该类型需要一个JSON数组。我也尝试过SwiftyJSON但是我在alamofire行上遇到了不同的编译器错误。
返回的错误是:
"errors" : [
{
"error_code" : "",
"message" : "addresses.city_locality: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[ShipEngine.Core.DTO.Address.AddressDTO]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'city_locality', line 1, position 17."
}
我使用的代码是:
let headers: HTTPHeaders = [
"content-type": "application/json",
"api-key": "API-KEY_HERE"
]
// not using SwiftyJSON
let parameters: [String: Any] = [
"name": "Mickey and Minnie Mouse",
"phone": "714-781-4565",
"company_name": "The Walt Disney Company",
"address_line1": "500 South Buena Vista Street",
"city_locality": "Burbank",
"state_province": "CA",
"postal_code": "91521",
"country_code": "US"
]
let url = "https://api.shipengine.com/v1/addresses/validate"
Alamofire.request(url, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers)
.responseJSON { (response) in
switch response.result {
case .success(let value):
let swiftyJson = JSON(value)
print ("return as JSON using swiftyJson is: \(swiftyJson)")
case .failure(let error):
print ("error: \(error)")
}
}
如果我使用SwiftyJSON并将我的参数声明更改为:
let parameters: JSON = [
"name": "Mickey and Minnie Mouse",
"phone": "714-781-4565",
"company_name": "The Walt Disney Company",
"address_line1": "500 South Buena Vista Street",
"city_locality": "Burbank",
"state_province": "CA",
"postal_code": "91521",
"country_code": "US"
]
我收到编译错误,说:
额外参数&#39;方法&#39;在电话中
在以下一行:
Alamofire.request(url, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers)
任何可以告诉我如何构建阵列的人的帮助都将非常感激。我尝试了各种格式并进行了大量搜索,但我没有运气......因为你猜测我是一个快速的新手!!
感谢您的帮助!
哦,最后一件事可以帮助一个人帮助我,这是来自ShipEngine网站使用这个api电话:
curl https://api.shipengine.com/v1/addresses/validate -X POST \
-H "Content-Type: application/json" \
-H "api-key: ElJkhJuQIRoFq/kDEblco4LpZqRCdYNIoAVG7SywSXw" \
-d '
[
{
"name": "Mickey and Minnie Mouse",
"phone": "714-781-4565",
"company_name": "The Walt Disney Company",
"address_line1": "500 South Buena Vista Street",
"city_locality": "Burbank",
"state_province": "CA",
"postal_code": "91521",
"country_code": "US"
}
]'