【发布时间】:2018-10-26 17:40:28
【问题描述】:
我最近开始使用 swift。我需要解码下面的json。
JSON 里面还有两个 JSON,第一个(验证)无关紧要。第二个(结果)内部有一个 JSON 数组(serviceCenter)。我需要每个服务员的信息。我尝试使用 servicecenter 作为可解码类来获取 servicenter 对象,但由于 JSON 没有正确的格式,我无法做到。
[
{
"validation": {
"bValid": true,
"sDescription": "Access true."
}
},
{
"result": {
"serviceCenter": [
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "3666",
"sVin": "6JDO2345",
"sMiles": "3666",
"bDamage": "1",
"dDateTime": "04-17-2018 9:38 AM"
},
{
"model": "F360",
"color": "Red",
"make": "Ferrari",
"sTag": "0010",
"sVin": "6JDO2347",
"sMiles": "80000",
"bDamage": "1",
"dDateTime": "04-17-2018 9:25 AM"
},
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "0009",
"sVin": "6JDO2345",
"sMiles": "25000",
"bDamage": "1",
"dDateTime": "04-17-2018 9:23 AM"
},
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "0003",
"sVin": "6JDO2345",
"sMiles": "20000",
"bDamage": "1",
"dDateTime": "04-12-2018 10:37 AM"
}
]
}
}
]
我尝试了很多,但我做不到。
这是我的代码,有人可以帮我吗
do {
let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
let h = type(of: parseoDatos )
print("'\(parseoDatos)' of type '\(h)'")
let contenido = parseoDatos[1]["result"]
if let services = contenido!! as? Dictionary<String, Array<Any>> {
for (_,serviceArray) in services {
for sc in serviceArray{
let h = type(of: sc )
print("'\(sc)' of type '\(h)'")
}
}
}
} catch {
print("json processing failed")
}
print sc 的结果是
{
bDamage = 1;
color = Purple;
dDateTime = "04-17-2018 9:38 AM";
make = "Aston Martin";
model = Vanquish;
sMiles = 3666;
sTag = 3666;
sVin = 6JDO2345;
}' of type '__NSDictionaryI'
【问题讨论】:
-
我想建议这个:你可以使用伟大的
SwiftJSON。 SwiftyJSON 使得在 Swift 中处理 JSON 数据变得很容易。 github.com/SwiftyJSON/SwiftyJSON -
你的可解码类是什么?请给我看你的代码。
-
正如@Glenn 所说,SwiftyJSON 是一个很棒的工具。或者,您可以查看 Swift 的
Codable协议。
标签: ios json swift parsing codable