0

我正在尝试将以下 JSON 发布到 api。以下是来自 Xcode 控制台的日志。

{
    address = (
        {
            city = 1;
            area = 1;
            "building_name" = "building";
        }
    );
    category = 1;
    inspection = 0;
    subCategory = (
        12
    );
}

所以这里的地址字段是嵌套 JSON 对象的数组。问题是地址字段在服务器端没有正确获取。我认为它认为包括城市、地区等在内的子字段作为单独的字典而不是作为一个整体的字典。以下是来自 Laravel 的日志。

array (
    'address' => 
    array (
        0 => 
        array (
           'city' => '1',
        ),
        1 => 
        array (
           'area' => '1',
        ),
        2 => 
        array (
           'building_name' => 'building',
        ),
    ),
    'category' => '1',
    'inspection' => '0',
    'subCategory' => 
    array (
        0 => '12',
    ),
)

基本上我想知道 Alamofire 是否以某种方式试图将它们 jsonify 两次,但无法避免它。我正在使用 Alamofire 4.7.2 和 Gloss 2.0,服务器端基于 Laravel。

4

2 回答 2

0

那是因为我在使用URLEncoding,所以服务器端无法正确解析参数。切换到JSONEncoding,它工作得很好。

所以使用

JSONEncoding.default.encode(urlRequest, with: params)

代替

URLEncoding.queryString.encode(urlRequest, with: params)
于 2018-06-06T14:42:54.957 回答
0

无论您打印什么,它都绝对不是JSON。尝试用对象喂你的 Alamofire 方法Codable,这可能如下所示(在 Playground 中):

import Cocoa

struct Address: Codable {
    let city: Int
    let area: Int
    let building_name: String
}

struct Inspection : Codable {
    let address: Address
    let category: Int
    let inspection: Int
    let subCategory: [Int]
}

let inspection = Inspection(address: Address(city: 1, area: 1, building_name: "building"), category: 1, inspection: 0, subCategory: [12])

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

do {
    let jsonData = try encoder.encode(inspection)
    print(String(data: jsonData, encoding: .utf8)!)
} catch {
    print(error)
}

这将打印出以下 JSON:

{
    "inspection" : 0,
    "subCategory" : [
    12
    ],
    "category" : 1,
    "address" : {
        "building_name" : "building",
        "city" : 1,
        "area" : 1
    }
}

大致符合您上面提供的内容。不知道subCategory应该是什么,所以我猜了一下。这种方法的美妙之处在于为您提供了一个JSONDecoder非常棒的免费 JSON 解析器。尝试从这里构建(或告诉我们您的输出应该代表什么)。

于 2018-05-05T12:40:19.020 回答