2017-03-17 22 views
-2

我正在使用swift解析JSON。我來到一本空白的字典。我將如何解析這個到自定義對象?如何解析Swift中的空字典JSON?

**我在看Image **

}, 
     "name": "Al bake", 
     "image": {}, 
     "website": "", 
     "category": { 
      "id": "d59d2b1c-ca37-4c76-bb93-1c0ba967ee84", 
      "name": "Test Category", 
      "slug": "test-category", 
      "is_active": true 
     }, 
+0

爲什麼你需要分析它? –

+0

我只是想學習如何做到這一點=] – user7097242

+0

你的圖像鍵只是一個空的dictionary.Are你問如何解析json數據? –

回答

0

如果您需要image的價值,這應該是一個字典(空或含有鍵&值),你需要知道包含的類型它。

例如,假設下面的代碼包含在詞典:

"name": "Al bake", 
"image": {}, 
"website": "", 
"category": { 
    "id": "d59d2b1c-ca37-4c76-bb93-1c0ba967ee84", 
    "name": "Test Category", 
    "slug": "test-category", 
    "is_active": true 

你會做這樣的事情:

if let image = dictionary["image"] as? Dictionary<String, Any> { 
    print(image.description) 
} else { 
    print("Image does not contain a value") 
} 
+0

我想將它設置爲'null'? – user7097242

+0

您是想從整個JSON數據結構創建一個自定義對象,還是隻想檢索'image'鍵的值? –

+0

僅爲圖像創建一個自定義對象 – user7097242