【问题标题】:Convert JSON Data into Dictionary将 JSON 数据转换为字典
【发布时间】:2016-09-12 06:25:10
【问题描述】:

我正在尝试将此 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​)
        ​​​​}
    }
}

【问题讨论】:

  • 先获取json数据数组后获取字典。请检查您的 json 数据 'jsoneditoronline.org' 站点在字典后数组中的第一个 0 索引。
  • 您可以使用 SwiftyJSON 进行良好的 json 持久化练习...:)

标签: ios json swift nsdictionary


【解决方案1】:

您的响应是数组而不是字典,因此您需要从数组访问对象,而且您的 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)
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-04
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    相关资源
    最近更新 更多