gpt4 book ai didi

ios - 如何在 ios Swift 3 中从模型创建 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:11:33 25 4
gpt4 key购买 nike

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

public class SignUpUser {
public var fullName : String?
public var id : Int?
public var city : String?
public var email : String?
public var address : String?
public var lastName : String?
public var countryCode : String?
public var firstName : String?
public var zipCode : Int?
public var contactNumber : Int?
public var sex : String?
public var dob : String?
public var signupType : String?
public var verified : String?
public var emailTokenExpiration : String?
public var updatedAt : String?
public var createdAt : String?

/**
Returns an array of models based on given dictionary.

Sample usage:
let user_list = User.modelsFromDictionaryArray(someDictionaryArrayFromJSON)

- parameter array: NSArray from JSON dictionary.

- returns: Array of User Instances.
*/
public class func modelsFromDictionaryArray(array:NSArray) -> [SignUpUser]
{
var models:[SignUpUser] = []
for item in array
{
models.append(SignUpUser(dictionary: item as! NSDictionary)!)
}
return models
}

/**
Constructs the object based on the given dictionary.

Sample usage:
let user = User(someDictionaryFromJSON)

- parameter dictionary: NSDictionary from JSON.

- returns: User Instance.

*/

init?() {}


required public init?(dictionary: NSDictionary) {
fullName = dictionary["fullName"] as? String
id = dictionary["id"] as? Int
city = dictionary["city"] as? String
email = dictionary["email"] as? String
address = dictionary["address"] as? String
lastName = dictionary["lastName"] as? String
countryCode = dictionary["countryCode"] as? String
firstName = dictionary["firstName"] as? String
zipCode = dictionary["zipCode"] as? Int
contactNumber = dictionary["contactNumber"] as? Int
sex = dictionary["sex"] as? String
dob = dictionary["dob"] as? String
signupType = dictionary["signupType"] as? String
verified = dictionary["verified"] as? String
emailTokenExpiration = dictionary["emailTokenExpiration"] as? String
updatedAt = dictionary["updatedAt"] as? String
createdAt = dictionary["createdAt"] as? String
}


/**
Returns the dictionary representation for the current instance.

- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {

let dictionary = NSMutableDictionary()

dictionary.setValue(self.fullName, forKey: "fullName")
dictionary.setValue(self.id, forKey: "id")
dictionary.setValue(self.city, forKey: "city")
dictionary.setValue(self.email, forKey: "email")
dictionary.setValue(self.address, forKey: "address")
dictionary.setValue(self.lastName, forKey: "lastName")
dictionary.setValue(self.countryCode, forKey: "countryCode")
dictionary.setValue(self.firstName, forKey: "firstName")
dictionary.setValue(self.zipCode, forKey: "zipCode")
dictionary.setValue(self.contactNumber, forKey: "contactNumber")
dictionary.setValue(self.sex, forKey: "sex")
dictionary.setValue(self.dob, forKey: "dob")
dictionary.setValue(self.signupType, forKey: "signupType")
dictionary.setValue(self.verified, forKey: "verified")
dictionary.setValue(self.emailTokenExpiration, forKey: "emailTokenExpiration")
dictionary.setValue(self.updatedAt, forKey: "updatedAt")
dictionary.setValue(self.createdAt, forKey: "createdAt")

return dictionary
}

}

我正在尝试使用以下方式将对象转换为 JSON,但出现错误提示 “json 写入中的顶级类型无效”

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

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

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

“包装在其他类中……”

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

我不想用字典来做这个,因为我每次都必须写键,我更喜欢使用对象,所以如果有人有任何线索,请指导我。

最佳答案

在你的模型类中添加这个方法

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

关于ios - 如何在 ios Swift 3 中从模型创建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com