如何将模型对象序列化为JSON字符串 - Swift 3

时间:2017-02-14 10:24:08

标签: ios json

我的模特是

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);

任何有兴趣解决我的问题的人: - )

2 个答案:

答案 0 :(得分:5)

向班级添加属性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)!

答案 1 :(得分:-1)

        let text = "{\"UserLoginId\":\"Dilip\",\"SearchString\":\"tata\",\"TableName\":\"null\"}";
        if let data = text.data(using: .utf8) {
            do {
                let dictData = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
                let company = getCompanyRequestModel()
                company.userLoginId = dictData["UserLoginId"] as? String
                company.searchString = dictData["SearchString"] as? String
                company.tableName = dictData["TableName"] as? String
            } catch {
                print(error.localizedDescription)
            }
        }