Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在swift中从JSON响应中获取值?_Json_Swift - Fatal编程技术网

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

如何在swift中从JSON响应中获取值?,json,swift,Json,Swift,如何在swift中从JSON响应中获取值?在这里,我想循环order对象值,以便根据它们的键获取字典值。谁能给我一个解决方案吗 { "order": [ "abc", "def", "ghi", ], "posts": { "abc": { "id": "abc", "user_id": "q", "channel_id": "q

如何在swift中从JSON响应中获取值?在这里,我想循环order对象值,以便根据它们的键获取字典值。谁能给我一个解决方案吗

{
    "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"
        }
    }
}

下面是您可以做的,使用string.Encoding.utf8编码将JSON字符串更改为数据

然后应用JSONSerialization并将其转换为字典/数组:

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)

查看

上的苹果文档,您需要JSONSerialization或JSONDecoder。请搜索:。在我对这个问题的回答中,有一个关于如何阅读JSON的快速教程。很简单,你试过什么吗?谷歌一些教程,这里有一些好的/懒惰的工具:实际上jsonText是NSDictionary。那么我如何传递呢???@gunjan如果这是一本字典,它不需要序列化,你的问题是误导性的。@gunjan你到底想做什么,从字典中获取值很容易,让posts=myDictionary[posts]as?[String:Any]这是从字典中获取值的方式。查看此文档或apple文档,了解我是否需要order的值???@gunjan do myDictionary[order]as?[String],您是否查阅了apple文档中的词典?