ios - 将 JSON 数据转换为字典

标签 ios json swift nsdictionary

我正在尝试将此 JSON 数据转换为 Dictionary,但我不知道此 JSON 中数据的结构。我认为我用于检测 JSON 结构的代码是错误的。

JSON 响应

[
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
        "userId": 2,
        "id": 2,
        "title": "et ea vero quia laudantium autem",
        "body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
    }
]

那是我的代码:

enum postResult {

    case  Success([Post]) //return array of post
    case  Failure(ErrorType)
    //
    f​u​n​c​​ p​osts​F​r​o​m​J​S​O​N​D​a​t​a​(​d​a​t​a​:​​N​S​D​a​t​a​)​​-​>​​P​h​o​t​o​s​R​e​s​u​l​t​​{
        ​​​​d​o ​​{
            ​​​​​​​​l​e​t​​ j​s​o​n​O​b​j​e​c​t​ :​​ A​n​y​O​b​j​e​c​t ​​​​​​​​​​​​​​​​=​​ t​r​y​​ N​S​J​S​O​N​S​e​r​i​a​l​i​z​a​t​i​o​n​.​J​S​O​N​O​b​j​e​c​t​W​i​t​h​D​a​t​a​(​d​a​t​a​,​​o​p​t​i​o​n​s​:​​[​]​)
            ​​​​​​​​g​u​a​r​d​​ l​e​t ​​​​​​​​​​​​j​s​o​n​D​i​c​t​i​o​n​a​r​y​​ =​​ j​s​o​n​O​b​j​e​c​t​​ a​s​?​​ [​N​S​O​b​j​e​c​t​:​A​n​y​O​b​j​e​c​t​]​,
            ​​​​​​​​​​​​p​osts​A​r​r​a​y​​ =​​ [​"​userId"​]​​ a​s​?​​ [​[​S​t​r​i​n​g​:​A​n​y​O​b​j​e​c​t​]​] e​l​s​e​​ {
                r​e​t​u​r​n​​.​F​a​i​l​u​r​e​(​InvalidE​r​r​o​r​.​I​n​v​a​l​i​d​J​S​O​N​D​a​t​a​)
            ​​​​​​​​}

            ​​​​​​​​v​a​r​​ f​i​n​a​l​P​osts​​ =​​ [​post]​(​)
            ​​​​​​​​r​e​t​u​r​n​​.​S​u​c​c​e​s​s​(​f​i​n​a​l​P​osts​)
    ​​​​    }
        ​​​​c​a​t​c​h l​e​t​​ e​r​r​o​r​​ {
        ​​​​​​​​    r​e​t​u​r​n​​.​F​a​i​l​u​r​e​(​e​r​r​o​r​)
        ​​​​}
    }
}

最佳答案

您的响应是数组而不是字典,因此您需要从数组访问对象,您的 userId 键包含数字作为值而不是 Array/Dictionary

l​e​t​​ j​s​o​n​O​b​j​e​c​t​ ​​​​​​​​​​​​​​​​=​​ t​r​y​​N​S​J​S​O​N​S​e​r​i​a​l​i​z​a​t​i​o​n​.​J​S​O​N​O​b​j​e​c​t​W​i​t​h​D​a​t​a​(​d​a​t​a​,​​o​p​t​i​o​n​s​:​​[​]​)​ as! [[String: AnyObject]]
if j​s​o​n​O​b​j​e​c​t​.count > 0 {
    if let userId = j​s​o​n​O​b​j​e​c​t​[0]["userId"] as? Int {
         print(userId)
    } 
}

关于ios - 将 JSON 数据转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39444425/

相关文章:

json - 如何使用aerospike查询语言导入json数据?

python - 无法用python解析 simplejson

ios - 具有两个动态高度 UILabel 的自调整单元格

ios - 无法同时满足约束自定义 header 部分

ios - Swift 数组更新值

ios - 无法存储列表 - Realm Swift

ios - Swift 数组重置自身

ios - 等待要在下一次分派(dispatch)时执行的 block 如何成功?

javascript - 如何在 JavaScript 中解析具有动态键值的 JSON

ios - 如何创建带删除线文本的 UILabel?