简体   繁体   English

从JSON Swift创建结构或对象数组

[英]Create an array of struct or object from json swift

I have a JSON filled with a list of Vendors. 我有一个用供应商列表填充的JSON。 Whats the best and most efficient way of holding this as instances that are easily accessible within the class and passable through the project. 什么是最好的和最有效的方法来将其作为实例,这些实例可以在类中轻松访问并可以在项目中传递。 I was thinking of using struct as i haven't used them before. 我正在考虑使用struct,因为我以前从未使用过它们。 Is it better than using Object? 比使用对象好吗?

Below i have my Struct. 下面我有我的结构。

struct Vendor {
let name: String
let latitude: Double
let longitude: Double

init(dictionary: [String: Any]) {
    self.name = dictionary["name"] as? String ?? ""
    self.latitude = dictionary["Lat"] as? Double ?? 0.0
    self.longitude = dictionary["Lng"] as? Double ?? 0.0
}
init?(data: Data) {
    guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
    self.init(dictionary: json)
}
init?(json: String) {
    self.init(data: Data(json.utf8))
}

} }

My question is how would i create an Array from the JSON of this struct type. 我的问题是如何从此结构类型的JSON创建数组。

Thanks 谢谢

Yes, using a struct is a great way to encapsulate your data. 是的,使用struct是封装数据的好方法。 As long as the struct models your JSON accurately you can covert to and from JSON easily. 只要该struct准确地对JSON建模,您就可以轻松地与JSON进行隐蔽。

If you conform your struct to Codable then encoding and decoding to JSON is fairly simple: 如果使struct符合Codable则编码和解码为JSON相当简单:

import Foundation

// Conform to Codable
struct Vendor: Codable {
  let name: String
  let latitude: Double
  let longitude: Double
}

// create Array
var vendors = [Vendor]()
for i in 1...3 {
  let vendor = Vendor(name: "Foo", latitude: Double(i), longitude: 20.0)
  vendors.append(vendor)
}

// encode the Array into a JSON string
// convert to Data, then convert to String
if let jsonData = try? JSONEncoder().encode(vendors),
  let jsonString = String(data: jsonData, encoding: .utf8) {
  print(jsonString)

  // [{"name":"Foo","longitude":20,"latitude":1},{"name":"Foo","longitude":20,"latitude":2},{"name":"Foo","longitude":20,"latitude":3}]

  // decode the JSON string back into an Array
  // convert to Data, then convert to [Vendor]
  if let vendorData = jsonString.data(using: .utf8),
    let vendorArray = try? JSONDecoder().decode([Vendor].self, from: vendorData) {
    print(vendorArray)

    // [__lldb_expr_8.Vendor(name: "Foo", latitude: 1.0, longitude: 20.0), __lldb_expr_8.Vendor(name: "Foo", latitude: 2.0, longitude: 20.0), __lldb_expr_8.Vendor(name: "Foo", latitude: 3.0, longitude: 20.0)]
  }
}

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

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