serialization - 获取 Swift 类的属性列表

标签 serialization enums swift

我正在尝试获取 swift 类的属性列表。有类似的问题herehere 。除了某些类型没有从 class_copyPropertyList 返回之外,我的一切都正常。到目前为止我测试过的有 Int? 和枚举。下面有一个我正在尝试的示例类。

enum PKApiErrorCode: Int {
    case None = 0
    case InvalidSignature = 1
    case MissingRequired = 2
    case NotLoggedIn = 3
    case InvalidApiKey = 4
    case InvalidLogin = 5
    case RegisterFailed = 6
}

class ApiError: Serializable {
    let code: PKApiErrorCode?
    let message: String?
    let userMessage: String?

    init(error: JSONDictionary) {
        code = error["errorCode"] >>> { (object: JSON) -> PKApiErrorCode? in
            if let c = object >>> JSONInt {
                return PKApiErrorCode.fromRaw(c)
            }

            return nil
        }

        message = error["message"] >>> JSONString
        userMessage = error["userMessage"] >>> JSONString
    }
}

可序列化类(在 https://gist.github.com/turowicz/e7746a9c035356f9483d 的帮助下)是

public class Serializable: NSObject, Printable {
    override public var description: String {
        return "\(self.toDictionary())"
    }
}

extension Serializable {
     public func toDictionary() -> NSDictionary {
        var aClass : AnyClass? = self.dynamicType
        var propertiesCount : CUnsignedInt = 0
        let propertiesInAClass : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount)
        var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()
        for var i = 0; i < Int(propertiesCount); i++ {

            var property = propertiesInAClass[i]
            var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
            var propType = property_getAttributes(property)
            var propValue : AnyObject! = self.valueForKey(propName);
            if propValue is Serializable {
                propertiesDictionary.setValue((propValue as Serializable).toDictionary(), forKey: propName)
            } else if propValue is Array<Serializable> {
                var subArray = Array<NSDictionary>()
                for item in (propValue as Array<Serializable>) {
                    subArray.append(item.toDictionary())
                }
                propertiesDictionary.setValue(subArray, forKey: propName)
            } else if propValue is NSData {
                propertiesDictionary.setValue((propValue as NSData).base64EncodedStringWithOptions(nil), forKey: propName)
            } else if propValue is Bool {
                propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName)
            } else if propValue is NSDate {
                var date = propValue as NSDate
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "Z"
                var dateString = NSString(format: "/Date(%.0f000%@)/", date.timeIntervalSince1970, dateFormatter.stringFromDate(date))
                propertiesDictionary.setValue(dateString, forKey: propName)

            } else {
                propertiesDictionary.setValue(propValue, forKey: propName)
            }
        }

        return propertiesDictionary
    }

    public func toJSON() -> NSData! {
        var dictionary = self.toDictionary()
        var err: NSError?
        return NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error: &err)
    }

    public func toJSONString() -> NSString! {
        return NSString(data: self.toJSON(), encoding: NSUTF8StringEncoding)
    }
}

字符串似乎仅在可选值是有效值时才出现,并且如果对象是枚举或 Int,则代码永远不会出现在对象上,除非 Int 有默认值。

感谢您提供有关获取类的所有属性(无论它们是什么)的任何建议。

最佳答案

我在苹果开发者论坛上收到了有关此问题的回复:

“class_copyPropertyList 仅显示公开给 Objective-C 运行时的属性。Objective-C 无法表示 Swift 枚举或非引用类型的可选值,因此这些属性不会公开给 Objective-C 运行时。”

Source

因此,总而言之,目前无法使用此方法序列化为 JSON。您可能需要考虑使用其他模式来完成此操作,例如将序列化任务分配给每个对象,或者可能使用 reflect() method将对象序列化为 JSON。

关于serialization - 获取 Swift 类的属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25632210/

相关文章:

ios - 用户位置不会出现在 Xcode 的模拟器中

ios - SwiftUI:在主视图上呈现模态(实际上不是模态) View 时,如何限制 View 的可点击区域?

serialization - multiprocessing.pool.MaybeEncodingError : Error sending result: Reason: 'TypeError("cannot serialize '_io.BufferedReader' object", )'

java - J2ME序列化

c++ - 加密和序列化 STL 字符串和其他容器

java - 编写按类获取/返回任何枚举常量的方法

python - python 中的枚举有什么好的用例?

Spring 数据 RedisTemplate : Serializing the Value and HashValue

java - 区分枚举和字段

ios - Swift `Decodable` 不适用于嵌套的 JSON 对象,除非嵌套是一个数组