【问题标题】:How to convert JSON to another type with SwiftJSON如何使用 SwiftJSON 将 JSON 转换为另一种类型
【发布时间】:2015-09-14 04:48:48
【问题描述】:

我尝试使用 Alamofire + SwiftJSON 从 Web 服务中获取 json 数据,但我无法将 JSON 类型转换为另一种类型

我的代码

 var product:JSON = []

 override func viewDidLoad() 

 { Alamofire.request(.GET, URL).responseJSON { (request, response, json, error) in 
   if json != nil { 
   self.product = JSON(json!) 
   let data = self.product["product"] 
    self.product = JSON(data!)

我希望将 json 数据输入 product:[NSDictionary] 以在我的 collectionViewCell 中显示标题名称或 id。请一些建议。 ——

Json 数据响应

{ 
  "product":{ 
  "title":"Night Cream", 
  "id":4573, 
  "created_at":"2015-08-21T07:54:09Z", 
  "updated_at":"2015-08-27T01:37:06Z", 
} 
}

如何将数据(JSON 类型)转换为字典以便将来使用?

【问题讨论】:

  • 真正的问题是什么?你不能写一些代码来转换它吗?在不知道您的要求(预期输出)的情况​​下,这个问题无法回答。
  • 问题是如何将数据转换为 NSDictionary。当我尝试“ let data = jsonObj["product".dictionary 它不起作用。先生,我该怎么做。
  • 首先,您不想将其转换为 NSDictionary。其次,定义“不工作”。在此处发布代码和错误消息将有所帮助。如果您真正阅读错误消息并尝试理解它会更好。
  • My code var product:[NSDictionary] = [] override func viewDidLoad() { Alamofire.request(.GET, URL).responseJSON { (request, response, json, error) in if json ! = nil { var jsonObj = JSON(json!) let data = jsonObj["product"] self.product = data // 不能赋值 [String:JSON] 类型的值?到 [NSDictionary] 类型的值 // 错误消息我希望将 json 数据输入到 product:[NSDictionary] 以在我的 collectionViewCell 中显示标题名称或 id。请给点建议。
  • 你应该编辑你的问题而不是把代码放在评论中。

标签: json swift swifty-json


【解决方案1】:
var product:[String:JSON] = [String:JSON]()

    override func viewDidLoad() 
         {
              Alamofire.request(YOUR_URL, method: .get, parameters: nil, encoding:  URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
                     switch(response.result) 
                     {
                    case .success(_):
                         let dict = JSON(response.result.value ?? "").dictionaryValue
                         self.product=dict["product"].dictionaryValue
                             break
                    case .failure(_):
                        // The network connection was lost please try again
                        break
                     }
                }
        }

按照上面的代码获取您的解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    相关资源
    最近更新 更多