[英]JS Object to Swift Struct
我在將數據(就像從端點獲取的JSON一樣)解析到Swift結構時遇到了困難。 似乎我從端點獲取的數據不是有效的JSON(至少不是所有的對象都在查看object =(...)的結構),所以我無法解碼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)")
}
我得到的錯誤:
Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 6." UserInfo={NSDebugDescription=No string key for value in object around character 6.})))
您很可能通過使用字符串插值創建來傳遞錯誤的數據對象。 如果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
創建正確的數據對象,並將Response
error
類型從Optional
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)
})
}
輸出:
Optional("testing1")
Optional("testing2-1")
Optional("testing2-2")
Optional("testing3-1")
Optional("testing3-2")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.