gpt4 book ai didi

swift - Alamofire + 光泽 : nested JSON array not working

转载 作者:行者123 更新时间:2023-11-30 11:31:42 25 4
gpt4 key购买 nike

我正在尝试将以下 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。

最佳答案

无论你打印出什么,它绝对不是 JSON。尝试使用 Codable 对象为您的 Alamofire 方法提供数据,这可能如下所示(在 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 解析器,这真的很棒。尝试从这里构建(或告诉我们您的输出应该代表什么)。

关于swift - Alamofire + 光泽 : nested JSON array not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50188835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com