【问题标题】:JSON response from server in Swift来自 Swift 中服务器的 JSON 响应
【发布时间】:2017-05-09 07:54:50
【问题描述】:

我在 swift 3 中调用 api。从 api 我得到 JSON 字符串格式的响应。如何在 Swift 中将该 JSON 字符串转换为字典或数组。该 JSON 字符串还包含更多的数组和字典。

我尝试过使用 EVReflection 工具。它只转换字典中的上层 JSON 对象。嵌套字典和数组仍然是字符串格式。

【问题讨论】:

标签: ios json swift dictionary swift3


【解决方案1】:

试试这样,响应是 [String: Any] 所以你必须转换为任何类型

DispatchQueue.main.async {
    do {
        if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
            let j = json as NSDictionary
            guard let resp = response as? HTTPURLResponse
                else {
                    // No response from server
                    return
            }

            if resp.statusCode == 200 {
                // You can put here some callback, this is a data you need
            } else {
               // Here is some error
            }
        }
    } catch {
        // And this is a error from server
    }
}

【讨论】:

  • 从 Swift Dictionary 到 Foundation NSDictionary 的类型转换会丢弃类型信息。不要那样做。
  • @vadian 我同意,但我认为出于提问的目的,可以得到想法。
  • 最好只建议 Swift 原生集合类型
【解决方案2】:

您应该会收到 jsonData,您可以直接尝试 JSONSerialization。

如果出于任何原因您将其作为 json String 接收,则必须先将该字符串转换为 jsonData

// Here you have to convert Json String to jsonData
// if it's not Json String then skip this line
let jsonData = jsonString.data(using: .utf8)

// Try to convert it to json object
do {
       let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String : Any]
       // now you can try to parse your json


      } catch let error as NSError {
          print(error.localizedDescription)
      }

或者像@Jay 提到的那样使用 Swiftyjson

【讨论】:

  • You have to change that string to jsonData 不,他们必须首先从服务器获取正确的 JSON 数据,而不是 JSON 字符串。 ;)
  • 我的回答是基于问题将 json 字符串转换为正确的 json 对象。将 json 设置为字符串的原因有很多,您必须手动将其转换回 json 数据。
  • 我没有说你的答案是错误的(你的答案唯一的“问题”是这个内容已经被给出了很多很多次)。我要说的是,这个 JSON 字符串通常是由 JSON 数据生成的……导致无用的转换。 OP 应该注意的常见错误。
  • 是的,你的权利。我会更新我的答案,让他明白?
  • 一如既往,永远不要在 Swift 中使用 .mutableContainers。该选项完全没有意义(以及.mutableLeaves)。删除options 参数。 Swift 3 中的 JSON 字典是 [String:Any]
猜你喜欢
  • 2017-12-02
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 2011-01-26
  • 2013-06-23
  • 2023-04-11
相关资源
最近更新 更多