如何从 ios Swift 中的模型创建 JSON 3
How to create JSON from Model in ios Swift 3
我已经为用户创建了模型 class,如下所示。
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 但出现错误 "invalid top-level type in json write"
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 对象包装在其他 class 对象中,但没有成功。
"Wrapping inside other class..."
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!)
}
我不想用字典来做这个,因为我每次都必须写键,我更喜欢使用对象,所以如果有人有任何线索,请指导我。
在您的模型中添加此方法class
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
}
这将给出模型的字典表示 class
这样您就可以访问 youclassObj.toDictionary()
并按照要求进行操作:Convert Dictionary to JSON in Swift
我已经为用户创建了模型 class,如下所示。
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 但出现错误 "invalid top-level type in json write"
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 对象包装在其他 class 对象中,但没有成功。
"Wrapping inside other class..."
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!)
}
我不想用字典来做这个,因为我每次都必须写键,我更喜欢使用对象,所以如果有人有任何线索,请指导我。
在您的模型中添加此方法class
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
}
这将给出模型的字典表示 class
这样您就可以访问 youclassObj.toDictionary()
并按照要求进行操作:Convert Dictionary to JSON in Swift