Swift可以将类/结构数据转换为字典吗?

时间:2017-10-06 02:59:45

标签: swift class object dictionary

例如:

class Test {
    var name: String;
    var age: Int;
    var height: Double;
    func convertToDict() -> [String: AnyObject] { ..... }
}

let test = Test();
test.name = "Alex";
test.age = 30;
test.height = 170;

let dict = test.convertToDict();

dict将有内容:

{"name": "Alex", "age": 30, height: 170}

这可以在Swift中使用吗?

我可以像字典一样访问类,例如可能使用:

test.value(forKey: "name");

或类似的东西?

感谢。

3 个答案:

答案 0 :(得分:27)

您只需向struct添加计算属性即可返回值Dictionary。请注意,Swift本机字典类型没有任何名为value(forKey:)的方法。您需要将Dictionary转换为NSDictionary

struct Test {
    let name: String
    let age: Int
    let height: Double
    var dictionary: [String: Any] {
        return ["name": name,
                "age": age,
                "height": height]
    }
    var nsDictionary: NSDictionary {
        return dictionary as NSDictionary
    }
}

您还可以按照@ColGraff发布的链接答案的建议扩展Encodable协议,使其适用于所有Encodable结构:

struct JSON {
    static let encoder = JSONEncoder()
}
extension Encodable {
    subscript(key: String) -> Any? {
        return dictionary[key]
    }
    var dictionary: [String: Any] {
        return (try? JSONSerialization.jsonObject(with: JSON.encoder.encode(self))) as? [String: Any] ?? [:]
    }
}
struct Test: Codable {
    let name: String
    let age: Int
    let height: Double
}

let test = Test(name: "Alex", age: 30, height: 170)
test["name"]    // Alex
test["age"]     // 30
test["height"]  // 170

答案 1 :(得分:4)

聚会晚了一点,但是对于JSONEncoderJSONSerialization来说,这是一个很好的机会。 公认的答案确实触及了这一点,该解决方案使我们每次访问密钥时都可以调用JSONSerialization,但是思路相同!

extension Encodable {

    /// Encode into JSON and return `Data`
    func jsonData() throws -> Data {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        encoder.dateEncodingStrategy = .iso8601
        return try encoder.encode(self)
    }
}

如果应该将JSONSerialization表示为JSON中的对象(例如,Swift Dictionary将是JSON数组),则可以使用Encodable创建一个Array < / p>

这是一个例子:

struct Car: Encodable {
    var name: String
    var numberOfDoors: Int
    var cost: Double
    var isCompanyCar: Bool
    var datePurchased: Date
    var ownerName: String? // Optional
}

let car = Car(
    name: "Mazda 2",
    numberOfDoors: 5,
    cost: 1234.56,
    isCompanyCar: true,
    datePurchased: Date(),
    ownerName: nil
)

let jsonData = try car.jsonData()

// To get dictionary from `Data`
let json = try JSONSerialization.jsonObject(with: jsonData, options: [])
guard let dictionary = json as? [String : Any] else {
    return
}

// Use dictionary

guard let jsonString = String(data: jsonData, encoding: .utf8) else {
    return
}

// Print jsonString
print(jsonString)

输出:

{
  "numberOfDoors" : 5,
  "datePurchased" : "2020-03-04T16:04:13Z",
  "name" : "Mazda 2",
  "cost" : 1234.5599999999999,
  "isCompanyCar" : true
}

答案 2 :(得分:2)

您可以像这样使用Reflection和Mirror使其更具动态性,并确保您不会忘记属性。

struct Person {
  var name:String
  var position:Int
  var good : Bool
  var car : String

  var asDictionary : [String:Any] {
    let mirror = Mirror(reflecting: self)
    let dict = Dictionary(uniqueKeysWithValues: mirror.children.lazy.map({ (label:String?,value:Any) -> (String,Any)? in
      guard label != nil else { return nil }
      return (label!,value)
    }).compactMap{ $0 })
    return dict
  }
}


let p1 = Person(name: "Ryan", position: 2, good : true, car:"Ford")
print(p1.asDictionary)

[“ name”:“ Ryan”,“ position”:2,“ good”:true,“ car”:“ Ford”]