Ios 如何使用SwiftyJSON解析JSON数组对象?
我有一个包含数组对象列表的JSON文件。我无法解析那个json文件 我已经尝试过这个代码,但它不起作用Ios 如何使用SwiftyJSON解析JSON数组对象?,ios,swift,swift3,swifty-json,Ios,Swift,Swift3,Swifty Json,我有一个包含数组对象列表的JSON文件。我无法解析那个json文件 我已经尝试过这个代码,但它不起作用 if let tempResult = json[0]["sno"].string{ print("Temp Result is \(tempResult)") } else { print(json[0]["sno"].error!) print("Temp Result didn't worked") } 这
if let tempResult = json[0]["sno"].string{
print("Temp Result is \(tempResult)")
}
else {
print(json[0]["sno"].error!)
print("Temp Result didn't worked")
}
这是我的JSON文件
[
{
"sno": "21",
"title": "title 1",
"tableid": "table 1"
},
{
"sno": "19",
"title": "title 222",
"tableid": "table 222"
},
{
"sno": "3",
"title": "title 333",
"tableid": "table 333"
}
]
实际上,最好为数组中的对象定义一个结构
public struct Item {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let sno = "sno"
static let title = "title"
static let tableid = "tableid"
}
// MARK: Properties
public var sno: String?
public var title: String?
public var tableid: String?
// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public init(object: Any) {
self.init(json: JSON(object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public init(json: JSON) {
sno = json[SerializationKeys.sno].string
title = json[SerializationKeys.title].string
tableid = json[SerializationKeys.tableid].string
}
}
您需要将JSON数组映射到Item对象
var items = [Item]()
if let arrayJSON = json.array
items = arrayJSON.map({return Item(json: $0)})
}
抛弃SwiftyJSON,改用Swift内置的
Codable
处理模型对象:
typealias Response = [ResponseElement]
struct ResponseElement: Codable {
let sno, title, tableid: String
}
do {
let response = try JSONDecoder().decode(Response.self, from: data)
}
catch {
print(error)
}
其中,
data
是从API获得的原始JSON数据。首先,用JSON数据/文件制作一个模型。然后,您现在可以使用SwiftyJSON。因此,如果您有一个名为“MyModel”的模型类。然后你可以拥有一个MyModel对象数组,因为你的数据/文件是一个数组。谢谢@Glenn的回答。我是iOS的初学者,所以一个示例代码或参考链接会很有帮助。如果你是初学者,那么我建议你看看Swift内置的json支持,google“Swift codable”。这是最常用的,而且非常好,因此获得帮助和查找相关信息会容易得多。你能解释一下“不工作”是什么意思,并说明你是如何得到JSON和如何解析它的吗?