【问题标题】:Fetch value of dictionary from JSON从 JSON 中获取字典的值
【发布时间】:2021-09-16 15:17:28
【问题描述】:

我想从 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 直接转换为字符串数组的替代解决方案。

【问题讨论】:

  • 我怀疑你有从 json 返回的字典。您有一个具有 text 属性的匿名类列表。
  • 如果你真的有一本字典,那么使用 Values[] 属性。它将返回一个字符串列表。
  • @TMcKeown 我认为您将 C# 和 Swift 混为一谈。 OP 询问 Swift 并且您的 cmets 指的是 C# 概念(匿名类和字典的 Values[] 属性)
  • 啊。我以为这是c#。哈哈好的thx

标签: ios arrays swift dictionary


【解决方案1】:

调整代码:

    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]();

【讨论】:

  • 如果 JSON 对象由于强制解包 (as!) 不包含“文本”键,let items: [String] = allText.map { $0["text"] }.compactMap { ($0 as! String) } 行将崩溃。您可以通过将其更改为let items: [String] = allText.compactMap { $0["text"] as? String } 来简化该行并修复崩溃
  • 你的代码更好,我已经调整了代码,非常感谢!@idz
  • 还有一件事......(据我所知)没有真正需要在textList 中创建items 的新副本。否则,很好的答案!
  • 我不确定问题中的 textsList 是否是全局变量。返回的结果可能是需要在别处显示的菜单。@idz
  • 我也可以从您的解决方案中获取字符串数组,但在调用实例方法 append 时仍然出现不完全匹配的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多