繁体   English   中英

如何使用 SwiftyJSON 解析 JSON 数组对象?

[英]How to parse JSON Array Objects with SwiftyJSON?

我有一个包含数组对象列表的 JSON 文件。 我无法解析那个 json 文件

我试过这段代码,但没有用

   if let tempResult = json[0]["sno"].string{
        print("Temp Result is \(tempResult)")
    }
    else {
        print(json[0]["sno"].error!) 
        print("Temp Result didn't worked")
    }

这是我的 JSON 文件

[
  {
  "sno": "21",
  "title": "title 1",
  "tableid": "table 1"
  },
  {
  "sno": "19",
  "title": "title 222",
  "tableid": "table 222"
  },
  {
   "sno": "3",
   "title": "title 333",
   "tableid": "table 333"
   }
]

实际上,最好为 Array 中的对象定义一个结构体。

public struct Item {

  // MARK: Declaration for string constants to be used to decode and also serialize.
  private struct SerializationKeys {
    static let sno = "sno"
    static let title = "title"
    static let tableid = "tableid"
  }

  // MARK: Properties

  public var sno: String?
  public var title: String?
  public var tableid: String?

  // MARK: SwiftyJSON Initializers
  /// Initiates the instance based on the object.
  ///
  /// - parameter object: The object of either Dictionary or Array kind that was passed.
  /// - returns: An initialized instance of the class.
  public init(object: Any) {
    self.init(json: JSON(object))
  }

  /// Initiates the instance based on the JSON that was passed.
  ///
  /// - parameter json: JSON object from SwiftyJSON.
  public init(json: JSON) {
    sno = json[SerializationKeys.sno].string
    title = json[SerializationKeys.title].string
    tableid = json[SerializationKeys.tableid].string
  }
}

并且您需要将 JSON 数组映射到 Item 对象。

var items = [Item]()
if let arrayJSON = json.array
  items = arrayJSON.map({return Item(json: $0)})
}

抛弃 SwiftyJSON 并使用 Swift 的内置Codable代替模型对象:

typealias Response = [ResponseElement]

struct ResponseElement: Codable {
    let sno, title, tableid: String
}

do {
   let response = try JSONDecoder().decode(Response.self, from: data)
}
catch {
   print(error)
}

其中data是您从 API 获得的原始 JSON 数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM