我有这样的 json:
{"result":0,"data":[{\"ID":7,"TITLE":"123"},{\"ID":8,"TITLE":"123"}]}
我有这样的结构:
struct ResponseResult: Decodable {
let result: Int
let data: [IdResponseResult]
}
struct IdResponseResult: Decodable {
let ID: Int
let TITLE: String
}
所以,当我这样运行请求时:
Alamofire.request("https://xxx.xxx.xxx",headers:headers).responseJSON { response in
if let json = response.data {
let decoder = JSONDecoder()
let result = try? decoder.decode(ResponseResult.self, from: json)
print(response.value)
completion(result)
}
}
并打印 response.value 我得到这个:
data = (
{
"ID" = 7;
TITLE = 123;
},
{
"ID" = 8;
TITLE = 123;
}
);
result = 0;
}
我无法解析它。我该如何解决??
最佳答案
解码失败是由resp2
结构体引起的
struct resp2: Decodable {
let ID: Int
let TITLE: String
}
您正在定义 TITLE:String
,但在 JSON 中您有一个 Int
"TITLE":123
。
如果您真的想要一个 String
(有意义,因为它是一个“标题”),您可能需要修复服务器端。
编辑:
我尝试了现在的 Decodable,我能够恢复你的结构,你可以检查:
let string = "{\"result\": 0,\"data\": [{\"ID\": 7,\"TITLE\": \"123\"}, {\"ID\": 8,\"TITLE\": \"123\"}]}"
let data = string.data(using: .utf8)
do {
let decoder = JSONDecoder()
let result = try? decoder.decode(ResponseResult.self, from: data!)
print(result?.data.first?.TITLE ?? "") // 123
} catch _ {
}
那么我想当您从服务接收数据时一定有一些奇怪的事情。
关于ios - swift 4错误的json数组解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865785/