在Swift 3中解析JSON时出错

时间:2018-01-09 11:42:49

标签: json swift xcode swift3

1。这是响应字符串

{"error_msg": null,"applicationStateJson": {"notifications_size": "0","dfilterlogin": 1,"loginstype": null,"email_status": "0","address_status": "0","defaultfiltername": "hyderabad","login_status": "1","defaultfilterid": 145,"profile_id": null,"freelancer": "Y","otp_status": "1","notifications": []},"status": null}

2。下面是一个完美的JSONObject,我使用JSONLint

{
"error_msg": null,
"applicationStateJson": {
    "notifications_size": "0",
    "dfilterlogin": 1,
    "loginstype": null,
    "email_status": "0",
    "address_status": "0",
    "defaultfiltername": "hyderabad",
    "login_status": "1",
    "defaultfilterid": 145,
    "profile_id": null,
    "freelancer": "Y",
    "otp_status": "1",
    "notifications": []
},
"status": null
}

第3。当我在Swift 3中尝试以下代码时

let json1 = try? JSONSerialization.jsonObject(with: data, options: [])

                    if let object = json1 as? [String: Any]{

                        if let applicationState = object["applicationStateJson"] as? [String: Any]{
                            print("applicationState   \(applicationState)")
                        }
                    }

4。我得到了JSONObject,但它不是一个合适的JSONObject

(因为逗号更改为分号,空值更改为“&lt; null&gt;”然后将空数组[]更改为()) < / p>

Optional({
applicationStateJson =     {
    "address_status" = 0;
    defaultfilterid = 145;
    defaultfiltername = hyderabad;
    dfilterlogin = 1;
    "email_status" = 0;
    freelancer = Y;
    "login_status" = 1;
    loginstype = "<null>";
    notifications =         (
    );
    "notifications_size" = 0;
    "otp_status" = 1;
    "profile_id" = "<null>";
};
"error_msg" = "<null>";
status = "<null>";
})

我希望JSONObject与第2步一样,有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

要在Swift中读取和使用JSON响应,您不需要将JSON对象转换回JSON以获取特定部分。将数据加载到Swift类型后,您可以直接使用它来获取所需的部件。

所以解释我的观点的漫长道路......

let jsonData = jsonString.data(using: .utf8)!
let json1 = try? JSONSerialization.jsonObject(with: jsonData, options: [])

if let object = json1 as? [String: Any]{

    if let applicationState = object["applicationStateJson"] as? [String: Any]{
        print("applicationState   \(applicationState)")

        if let addressStatus = applicationState["address_status"] as? String {
            print(addressStatus)
        }
    }
}

使用Codable协议执行此操作的Swift 4方法

let jsonString = "{\"error_msg\": null,\"applicationStateJson\": {\"notifications_size\": \"0\",\"dfilterlogin\": 1,\"loginstype\": null,\"email_status\": \"0\",\"address_status\": \"0\",\"defaultfiltername\": \"hyderabad\",\"login_status\": \"1\",\"defaultfilterid\": 145,\"profile_id\": null,\"freelancer\": \"Y\",\"otp_status\": \"1\",\"notifications\": []},\"status\": null}"

struct ApplicationState: Codable {
    let notificationsSize: String
    let dFilterLogin: Int
    let loginsType: String?
    let emailStatus: String
    let addressStatus: String

    enum CodingKeys : String, CodingKey {
        case notificationsSize = "notifications_size"
        case dFilterLogin = "dfilterlogin"
        case addressStatus = "address_status"
        case loginsType = "loginstype"
        case emailStatus = "email_status"
    }
}

struct ApplicationStateResponse: Codable {
    let errorMsg: String?
    let applicationState: ApplicationState

    enum CodingKeys : String, CodingKey {
        case errorMsg = "error_msg"
        case applicationState = "applicationStateJson"
    }
}

let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
let response = try! decoder.decode(ApplicationStateResponse.self, from: jsonData)
let appState = response.applicationState

print(appState.addressStatus)

这两个都按预期打印0作为地址状态。一个人比另一个人更容易工作。

这个article解释了可编码协议,这将是一个很好的阅读。

答案 1 :(得分:0)

将Swift Dictionary对象转换为JSON字符串

if let theJSONData = try?  JSONSerialization.data(withJSONObject: applicationState, options: .prettyPrinted),
                                let theJSONText = String(data: theJSONData, encoding: String.Encoding.ascii) {
                                print("JSON string = \n\(theJSONText)")
                            }