这个问题在这里已经有了答案:
How to Make JSON from Array of Struct in Swift 3?
(1 个回答)
5年前关闭。
我的模型是
public class getCompanyRequestModel
{
public var userLoginId : String?
public var searchString : String?
public var tableName : String?
}
在 viewController 的 viewdidload 方法中,我创建了 getCompanyRequestModel 对象
var objGetCompany = getCompanyRequestModel()
objGetCompany.userLoginId = "Dilip";
objGetCompany.searchString = "tata";
objGetCompany.tableName = "null";
现在我想从 objGetCompany 获取 JSON 字符串,如下所示
"{\"UserLoginId\":\"Dilip\",\"SearchString\":\"tata\",\"TableName\":\"null\"}";
在 C# 中,我从下面的代码行获取 JSON 字符串
string JsonParameters = JsonConvert.SerializeObject(objGetCompany);
任何有兴趣解决我的问题的人:-)
最佳答案
添加属性 jsonRepresentation
上课:
var jsonRepresentation : String {
let dict = ["userLoginId" : userLoginId, "searchString" : searchString, "tableName" : tableName]
let data = try! JSONSerialization.data(withJSONObject: dict, options: [])
return String(data:data, encoding:.utf8)!
}
顺便说一句:Swift 中的类名应该以大写字母开头。
并且不要使用可选项作为懒惰的借口,不要编写初始化程序......
更新:
在 Swift 4 中有一个更聪明的方法:删除
jsonRepresentation
并采用Codable
public class CompanyRequestModel : Codable { ...
然后使用
JSONEncoder
let data = try JSONEncoder().encode(objGetCompany)
let jsonString = String(data: data, encoding: .utf8)!
关于ios - 如何将模型对象序列化为 JSON 字符串 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223594/