[英]How to create JSON from Model in ios Swift 3
我為用戶創建了模型類,如下所示。
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!)
}
在使用Google gson庫的Android中,我們可以輕松地將JSON轉換為Object,反之亦然,但在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!)
}
我不希望使用Dictionary進行此操作,因為每次都必須編寫鍵,所以我更喜歡使用對象,因此,如果有人有任何線索,請指導我。
在模型類中添加此方法
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()
一樣進行訪問
並按照要求進行操作: 在Swift中將Dictionary轉換為JSON
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.