如何在swift中从JSON响应中获取值?

时间:2018-03-02 09:25:32

标签: json swift

如何在swift中从JSON响应中获取值?在这里,我想循环订单对象值,以便根据其键获取字典值。任何人都可以建议我一个解决方案。

0xc0000005

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:使用String.Encoding.utf8编码将您的JSON字符串更改为数据

然后应用 JSONSerialization 并将其转换为Dictionary / Array:

let jsonText = """

{
    "order": [
    "abc",
    "def",
    "ghi",
    ],

"posts": {
    "abc": {
        "id": "abc",
        "user_id": "q",
        "channel_id": "qwer",
        "message": "dsd"
    },
    "def": {
        "id": "def",
        "user_id": "w",
        "channel_id": "werg",
        "message": "Gg"
    },
    "ghi": {
        "id": "ghi",
        "user_id": "v",
        "channel_id": "bnm",
        "message": "Ss"
    }
}
}
"""

var dictionary: [String: Any]?

if let data = jsonText.data(using: String.Encoding.utf8) {

do {
    dictionary = try JSONSerialization.jsonObject(with: data, options: [.allowFragments,.mutableLeaves]) as? [String: Any]

    if let myDictionary = dictionary {
        let posts = myDictionary["posts"] as? [String: Any]
        print(posts)

        print(posts?["abc"] as? [String: Any])
    }
} catch let error as NSError {
    print(error)
}
}

要根据订单获取消息,您可以执行以下操作:

let orders = (dictionary?["order"] as? [String]) ?? []

//message for abc
var posts = dictionary?["posts"] as? [String: Any]
var post = posts?[orders.first ?? ""] as? [String: Any]
var message = post?["message"]
print(message)

查看NSJSONSerialization

上的苹果文档