将json数据转换为[String:Any]时出错

时间:2016-12-22 22:09:30

标签: json casting swift3

我创建了一个下载json文件的数据任务。 json是一系列字典。这是数据样本:

[
  {
    "userName": "Elon Musk",
    "comment": "This is a fantastic Beer.  I highly recommend it!"
  },
  {
    "userName": "SuperUser Account",
    "comment": "I agree with Elon.. It rocks!"
  }
]

问题是我无法将json强制转换为[String: Any]。我只能把它投到[Any]。以下是相关代码:

 guard let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
        print("error trying to convert data to JSON")
        return
    }
    // now we have the json, let's just print it to prove we can access it
    print("The json is: " + json.description)

施放为[Any] json打印正常。演员失败了吗?

请问?

编辑..这是网址: http://www.smarttapp.com/DesktopModules/DnnSharp/DnnApiEndpoint/Api.ashx?method=GetCommentsFromArticleID&articleID=2240

1 个答案:

答案 0 :(得分:1)

你的json是array而不是字典..只是把它投到[[String:Any]]

  guard let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [[String: Any]] else {
       print("error trying to convert data to JSON")
       return
  }

  for dict in json {
      print(dict["userName"])
  }