[英]How to encode jsonarray on Swift 4 ios
我有一個這樣的 JSON 數組
[
{
"value" : "temp",
"value2" : "temp2",
"value3" : "temp3",
},
{
"value" : "temp";
"value2" : "temp2",
"value3" : "temp3",
}, {
"value" : "temp",
"value2" : "temp2",
"value3" : "temp3",
}
]
我嘗試在 swift 4 上為 ios 應用程序解析它。 我沒有找到關於這個主題的任何解決方案。 我已經嘗試了很多這樣的代碼
let jsonpars = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [AnyObject]
您提供的 JSON 無效。 正確的 JSON 格式應如下所示:
=
替換為:
;
用逗號結果應如下所示:
[
{
"value":"temp",
"value2":"temp2",
"value3":"temp3",
},
...
]
然后,您提供的解析代碼示例應該可以正常工作。
您的示例 JSON 看起來像解析后打印出來的內容。 例如:
let jsonpars = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [AnyObject]
print(jsonpars)
導致 JSON 輸出的調試版本:
[{
value = temp;
value2 = temp2;
value3 = temp3;
}, {
...
]
真正的JSON,你要解析的數據,必須有冒號和逗號。
使用quicktype ,我為您的示例生成了這個模型和轉換代碼(在更正語法問題之后):
import Foundation
struct Value: Codable {
let value, value2, value3: String
}
extension Array where Element == Value {
static func from(json: String, using encoding: String.Encoding = .utf8) -> [Value]? {
guard let data = json.data(using: encoding) else { return nil }
return [Value].from(data: data)
}
static func from(data: Data) -> [Value]? {
let decoder = JSONDecoder()
return try? decoder.decode([Value].self, from: data)
}
var jsonData: Data? {
let encoder = JSONEncoder()
return try? encoder.encode(self)
}
var jsonString: String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
}
然后你可以像這樣反序列化:
let values = [Value].from(json: """
[
{
"value": "temp",
"value2": "temp2",
"value3": "temp3"
},
{
"value": "temp",
"value2": "temp2",
"value3": "temp3"
},
{
"value": "temp",
"value2": "temp2",
"value3": "temp3"
}
]
""")!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.