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

时间:2018-09-22 16:13:35

标签: ios json swift

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

要检索我正在使用的数据:

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

要将数据转换为JSON字典,

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"]

修复-它需要{{1}},如果将其打印到控制台,则会再次打印整个词典。

预先感谢您的任何建议。

2 个答案:

答案 0 :(得分:2)

我认为最好使用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)
}

答案 1 :(得分:1)

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

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"])
   }
}