gpt4 book ai didi

ios - Swift 中特殊的 JSON 解析

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

我想构建一个 iOS 应用程序,我需要为此 JSON 字符串创建一个仅显示内容的数组:

[ {"content":"hello"}, {"content":"hi"}, {"content":"how are you?"} ]

结果应如下所示:

["hello", "hi", "how are you?"]

如何在 Swift 中做到这一点?

这是我在 ViewController.swift 文件中的代码:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let mList = "[{"content":"hello"},{"content":"hi"},{"content":"how are you?"}]"
let data = mList!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

最佳答案

let mList = "[{\"content\":\"hello\"},{\"content\":\"hi\"},{\"content\":\"how are you?\"}]"
let JSONData = mList.dataUsingEncoding(NSUTF8StringEncoding)!
var json: Array<AnyObject>!
do {
json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as? Array
} catch {
print(error)
}

var resultArray = [String]()
for item in json {
if let content = item["content"] as? String {
resultArray.append(content)
}
}
print("resultArray: \(resultArray)")

关于ios - Swift 中特殊的 JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37425105/

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