gpt4 book ai didi

arrays - Swift:从 JSON 中解析数组

转载 作者:行者123 更新时间:2023-11-30 10:04:47 24 4
gpt4 key购买 nike

[{"name":"Air Elemental","toughness":"4","printings":["LEA","BTD","7ED","8ED","9ED","10E","DD2","M10","DPA","ME4","DD3_JVC"]}]

我有一个 JSON,其中每个列表中有一个名为“printings”的数组,如下所示,我如何从每个列表中取出这个数组并将其转换为“LEA-BTD-7ED”之类的字符串。这是我到目前为止所拥有的,但它崩溃了。

let err : NSErrorPointer?
let dataPath = NSBundle.mainBundle().pathForResource("cardata", ofType: "json")
let data : NSData = try! NSData(contentsOfFile: dataPath! as String, options: NSDataReadingOptions.DataReadingMapped)
do{
var contents = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]

for var i = 0;i<contents.count;++i{

let printing = contents[i]["printings"] as! String
}
}

最佳答案

代码如下:

let path = dataPath!
if let JSONData = NSData(contentsOfFile: path)
{
do
{
if let dictionariesArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as?
[[String: AnyObject]]
{
for dictionary in dictionariesArray
{
if let printingsArray = dictionary["printings"] as? [String]
{
let printingsString = printingsArray.joinWithSeparator("-")
print(printingsString)
}
}
}

}
catch
{
print("Could not parse file at \(path)")
}
}

执行它会打印“LEA-BTD-7ED-8ED-9ED-10E-DD2-M10-DPA-ME4-DD3_JVC”

关于arrays - Swift:从 JSON 中解析数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36635687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com