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

时间:2019-01-09 06:10:59

标签: ios swift swift3 swifty-json

我有一个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"
   }
]

2 个答案:

答案 0 :(得分:2)

抛弃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数据。

答案 1 :(得分:1)

实际上,最好在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)})
}