我在将数据(就像从端点获取的JSON一样)解析到Swift结构时遇到了困难。看来我从端点获取的数据不是有效的JSON(至少不是所有的数据都查看 object =(...)的结构),所以我无法解码{{ 1}}。
我应该用另一种方式解析它吗?任何建议,不胜感激
我准备的结构是:
ListStruct
我从端点获取的数据示例:
struct Response:Codable {
let message:String?
let list:ListStruct?
let error:Bool?
}
struct ListStruct:Codable {
let object1:[Object1]?
let object2:[Object2]?
let object3:[Object3]?
}
struct Object1:Codable {
id:Int?
name:String?
}
...
编辑
我要如何解码:
["message": <null>, "list": {
object1 = (
{
id = 1;
name = "testing1";
}
);
object2 = (
{
files = (
);
id = 1;
name = "testing2-1";
photos = (
);
},
{
files = (
);
id = 2;
name = "testing2-2";
photos = (
);
systemId = 8;
}
);
object3 = (
{
id = 6;
name = "testing3-1";
},
{
id = 13;
name = "testing3-2";
}
);
}, "error": 0]
我得到的错误:
if let result = try JSONDecoder().decode(Response?.self, from: "\(response!)".data(using: .utf8)! ) {
print("\(result)")
}
答案 0 :(得分:2)
很可能是通过使用字符串插值创建来传递错误的数据对象。如果response
类型为Data
,则无需在下面的行中重新创建它,
if let result = try JSONDecoder().decode(Response?.self, from: "\(response!)".data(using: .utf8)! ) {
尝试按原样传递response
。如下所示,
if let result = try JSONDecoder().decode(Response?.self, from: response!) {
这是一个完整的可测试示例,其中使用有问题的json
创建了正确的数据对象,并且error
中的Response
类型从Optional
{{1} }到Bool
,
Int
用法:
struct Response:Codable {
let message:String?
let list:ListStruct?
let error: Int?
}
struct ListStruct: Codable {
let object1:[Object1]?
let object2:[Object2]?
let object3:[Object3]?
}
struct Object1: Codable {
var id:Int?
var name:String?
}
struct Object2: Codable {
var id:Int?
var name:String?
var systemId: Int?
}
struct Object3: Codable {
var id:Int?
var name:String?
}
输出:
let data = """
{"message": null,
"list": {
"object1": [
{
"id": 1,
"name": "testing1"
}
],
"object2" : [
{
"files" : [
],
"id" : 1,
"name" : "testing2-1",
"photos" : [
]
},
{
"files" : [
],
"id" : 2,
"name" : "testing2-2",
"photos" : [
],
"systemId" : 8
}
],
"object3" : [
{
"id" : 6,
"name" : "testing3-1",
},
{
"id" : 13,
"name" : "testing3-2",
}
]
},
"error": 0
}
""".data(using: .utf8)!
if let result = try! JSONDecoder().decode(Response?.self, from: data) {
result.list?.object1?.forEach({ obj in
print(obj.name)
})
result.list?.object2?.forEach({ obj in
print(obj.name)
})
result.list?.object3?.forEach({ obj in
print(obj.name)
})
}