gpt4 book ai didi

ios - 从 JSON 中获取字典的值

转载 作者:行者123 更新时间:2023-12-04 07:25:02 25 4
gpt4 key购买 nike

我想从 JSON 中获取字符串的值,我能够将 JSON 解析为 Dictionary 但无法转换为字符串数组
从服务器

    {
“ALL TEXT: [

{
"text": "hello"
},
{
"text": "hi"
},
{
"text": "how r u"
}
]
}
我只想将文本值附加到我的字符串数组“textsList”
    var textsList : [String]()
这是我试过的
            URLSession.shared.dataTask(with: request) { (data, response, err) in                               
let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, Any>


let AllText = json[“ALL TEXT”] as! [Dictionary<String, Any>]
let value = JSON(AllText)

AllText.forEach { fetch in
self.textsList.append(fetch.values) // ERROR no exact matches in call to instance method append
}

for(key, object) in value{
print(value) //output: {"text": "hello" },{"text": "hi" }
print(value.string) //output:nil
}



}.resume()
我只想将字典转换为数组,但也可以将 JSON 直接转换为字符串数组的替代解决方案。

最佳答案

调整代码:

    let string = """
{
"ALL TEXT": [
{
"text": "hello"
},
{
"text": "hi"
},
{
"text": "how r u"
}
]
}
"""

guard let data = string.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String, Any>,
let allText = json["ALL TEXT"] as? [Dictionary<String, Any>]
else {
DDLog("json fail")
return }
DDLog(allText) // [["text": hello], ["text": hi], ["text": how r u]]

let items: [String] = allText.compactMap { $0["text"] as? String }

var textsList = [String]()
textsList.append(contentsOf: items)

DDLog(items) //["hello", "hi", "how r u"]
DDLog(textsList) //["hello", "hi", "how r u"]
两个错误:
1. <"ALL TEXT> Missing right quote;
2. var textsList: [String]() =》var textsList = [String]();

关于ios - 从 JSON 中获取字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68262949/

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