简体   繁体   中英

Create an array of struct or object from json swift

I have a JSON filled with a list of Vendors. 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. 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.

Thanks

Yes, using a struct is a great way to encapsulate your data. As long as the struct models your JSON accurately you can covert to and from JSON easily.

If you conform your struct to Codable then encoding and decoding to JSON is fairly simple:

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)]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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