0

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

1 Answer 1

5

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)]
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.