我有像这样的JSON数组
[
{
"value" : "temp",
"value2" : "temp2",
"value3" : "temp3",
},
{
"value" : "temp";
"value2" : "temp2",
"value3" : "temp3",
}, {
"value" : "temp",
"value2" : "temp2",
"value3" : "temp3",
}
]
我尝试在swift 4 for ios app上解析它。 我找不到关于这个问题的任何解决方案。 我尝试了很多这样的代码
let jsonpars = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [AnyObject]
答案 0 :(得分:0)
您提供的JSON无效。正确的JSON格式应如下所示:
=
替换为:
;
醇>
结果应如下所示:
[
{
"value":"temp",
"value2":"temp2",
"value3":"temp3",
},
...
]
然后,您提供的解析代码示例应该可以正常工作。
您的示例JSON看起来像解析后打印出来的内容。例如:
let jsonpars = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [AnyObject]
print(jsonpars)
导致JSON输出的 debug 版本:
[{
value = temp;
value2 = temp2;
value3 = temp3;
}, {
...
]
真正的 JSON,您要解析的数据,必须有冒号和逗号。
答案 1 :(得分:0)
使用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"
}
]
""")!