在Swift 3中解析JSON时出错

在Swift 3中解析JSON时出错,json,swift,xcode,swift3,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": n

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

{
"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
}
(因为逗号变为分号,空值变为“”,然后空数组[]变为())

可选({
applicationStateJson={
“地址状态”=0;
defaultfilterid=145;
defaultfiltername=海得拉巴;
dfilterlogin=1;
“电子邮件状态”=0;
自由职业者=Y;
“登录状态”=1;
loginstype=“”;
通知=(
);
“通知大小”=0;
“otp_状态”=1;
“profile_id=”;
};
“错误消息”=“”;
地位=”;
})

我想要像步骤2一样的JSONObject,有什么帮助吗?

将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)")
                            }

在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)
        }
    }
}
使用可编码协议执行此操作的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。一个比另一个更容易操作


这篇文章对可编码协议进行了更多的解释,这将是一个很好的解读。

这是一样的,它刚刚从JSON字符串转换为Swift Dictionary对象。我如何再次更改它的JSON字符串?最后,我找到了方法,{如果让JSONDATA=try?JSONSerialization.data(使用JSONObject:applicationState,选项:.prettyPrinted),让jsontext=String(数据:theJSONData,编码:String.encoding.ascii){print(“JSON String=\n(theJSONText)”)}}我可以问一下为什么要将JSON字符串转换为Swift对象,然后再次部分创建JSON字符串吗?。听起来你在做一些你不需要做的事情,因为我想从JSON对象中解析JSON对象,也就是我想从响应中解析applicationStateJson如何使用你的代码获取applicationStateJson表单jsonString?你在问题中没有提到你只想要JSON字符串的一部分。