代码之家  ›  专栏  ›  技术社区  ›  user6631314

IOS/Swift:解析JSON数据和字典

  •  0
  • user6631314  · 技术社区  · 6 年前

    我试图解析通过API检索到的一些嵌套JSON,但在隔离特定的键值对时遇到了问题。事实上,我对JSON数据和通过序列化获得的字典之间的差异有些困惑。

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {                                                 
                    return
                } 
    

    为了将数据转换成JSON字典,我正在做

    do {
                    let stringDic = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
                } catch let error {
                    print(error)
                }
    

    Optional(["document_tone": {
        "tone_categories" =     (
                    {
                "category_id" = "emotion_tone";
                "category_name" = "Emotion Tone";
      and so forth
    

    我的问题是,如何才能得到一个唯一的值,比如密钥的值 category_name ?

    let myCat = stringDic["category_name"]
    

    let document_tone = stringDic?["document_tone"] 如果打印到控制台,只需重新打印整本字典。

    提前谢谢你的建议。

    2 回复  |  直到 6 年前
        1
  •  2
  •   vadian    6 年前

    很简单: () {} 是字典,编译器必须知道所有下标对象的静态类型:

    if let documentTone = stringDic?["document_tone"] as? [String:Any],
       let toneCategories = documentTone["tone_categories"] as? [[String:Any]] {
       for category in toneCategories {
           print(category["category_name"])
       }
    }
    
        2
  •  2
  •   Shehata Gamal    6 年前

    我觉得最好用 Decodable

    struct Root:Decodable {
         let documentTone : InnerItem 
    } 
    struct InnerItem:Decodable {
         let toneCategories: [BottomItem] 
    }  
    struct BottomItem:Decodable {
         let categoryId: String
         let categoryName: String 
    }
    

    do {
       let decoder = JSONDecoder()
       decoder.keyDecodingStrategy = .convertFromSnakeCase
       let result = try decoder.decode(Root.self, from: data)
       //print all names 
       result.documentTone.toneCategories.forEach {print($0.categoryName) }
    } catch {
      print(error)
    }