如何在ios Swift 3中从Model创建JSON

时间:2017-04-04 11:11:20

标签: ios json swift3 nsjsonserialization

我已为用户创建了模型类,如下所示。

let signUpuser =  SignUpUser()
        signUpuser?.fullName = "Teswt"
        signUpuser?.id = 1
        signUpuser?.city = "Test"
        signUpuser?.email = "Test"
        signUpuser?.address = "Test"
        signUpuser?.lastName = "Test"
        signUpuser?.countryCode = "Test"
        signUpuser?.firstName = "Test"
        signUpuser?.zipCode = 380004
        signUpuser?.contactNumber = 12345
        signUpuser?.sex = "Test"
        signUpuser?.dob = "Test"
        signUpuser?.signupType = "Test"
        signUpuser?.verified = "Test"
        signUpuser?.emailTokenExpiration = "Test"
        signUpuser?.updatedAt = "Test"
        signUpuser?.createdAt = "Test"

if let jsonData = try? JSONSerialization.data(withJSONObject: signUpuser, options: []) {
            let theJSONText = String(data: jsonData, encoding: .utf8)
            AppLog.debug(tag: TAG, msg: theJSONText!)
        }

我试图通过以下方式将对象转换为JSON,但是在json写入“顶级类型无效”时收到错误

let wrapperObject = JSONServerRequest(data: signUpuser)
        if let jsonData = try? JSONSerialization.data(withJSONObject: wrapperObject, options: []) {
            let theJSONText = String(data: jsonData, encoding: .utf8)
            AppLog.debug(tag: TAG, msg: theJSONText!)
        }

在使用Google的gson库的Android中,我们可以轻松地将JSON转换为Object,反之亦然,但在iOS中似乎有点困难。

我还尝试将SignupUser对象包装在其他类对象中,但没有运气。

“在其他课程中包装......”

{ role: 'toggledevtools'}

我不希望用词典做这个,因为我每次都要写密钥,我更喜欢使用对象,所以如果有人有任何线索,请指导我。

1 个答案:

答案 0 :(得分:6)

在模型类中添加此方法

func toDictionary() -> [String : Any] {

    var dictionary = [String:Any]()
    let otherSelf = Mirror(reflecting: self)

    for child in otherSelf.children {

        if let key = child.label {
            dictionary[key] = child.value
        }
    }

    print("USER_DICTIONARY :: \(dictionary.description)")

    return dictionary
}

这将给出模型类的字典表示 所以您可以访问youclassObj.toDictionary()

并按照要求进行操作:Convert Dictionary to JSON in Swift