【问题标题】:Json response gets only last row in swiftJson 响应仅在 swift 中获得最后一行
【发布时间】:2017-08-14 03:35:05
【问题描述】:

嗨,我正在尝试从服务器获取儿子的响应,以下是我在使用邮递员时从服务器获得的响应

{
  "stories": [
{
  "image_url": "http://storybox.dk/wp-content/uploads/2016/11/Hansa.jpg",
  "name": "New story",
  "story_key": "ahJlfnN0b3J5Ym94LWJhY2tlbmRyEgsSBVN0b3J5GICAgIC8oYIKDA"
},
{
  "image_url": "http://storybox.dk/wp-content/uploads/2016/11/Hansa.jpg",
  "name": "Story of Foo the fox.",
  "story_key": "ahJlfnN0b3J5Ym94LWJhY2tlbmRyEgsSBVN0b3J5GICAgID4woQKDA"
}]
}

但是当我尝试将故事标签内的值作为数组获取时,它只得到一个值
self.StoryListArr = (reponsedict.value(forKey: "stories") as?NSArray)!

 (
   {
    "image_url" = "http://storage.googleapis.com/storybox-backend.appspot.com/5649391675244544/Screenshot_from_2017-03-16_113338.png";
    name = "Story of Foo";
    "story_key" = ahJlfnN0b3J5Ym94LWJhY2tlbmRyEgsSBVN0b3J5GICAgID4woQKDA;
   }
)

请告知如何处理这个问题

当我尝试打印响应字典时,它只显示一个值

{
stories =     (
            {
        "image_url" = "http://storage.googleapis.com/storybox-backend.appspot.com/5649391675244544/Screenshot_from_2017-03-16_113338.png";
        name = "Story of Foo";
        "story_key" = ahJlfnN0b3J5Ym94LWJhY2tlbmRyEgsSBVN0b3J5GICAgID4woQKDA;
    }
);
}

【问题讨论】:

  • 试试reponsedict["stories"] as! [[String:Any]]
  • 使用 swifty json。这要容易得多
  • 我会推荐使用 ObjectMapper。 Here 就是一个例子
  • 嗨,我尝试打印 responsedict,但它在 stories 标签内只显示一个值,我已将其添加到问题中
  • 我认为问题出在您的 api 上。再次检查返回数据。

标签: ios json swift swift3 nsjsonserialization


【解决方案1】:

没有理由在 Swift 中使用 NSArray。只需将对象转换为 [Dictionary]。

if let stories = responsedict["stories"] as? [Dictionary<String,String>] {
    print(stories) 
}

【讨论】:

  • 当我尝试打印响应字典时,它只显示一个值print(reponsedict) { stories = ( { "image_url" = "http://storage.googleapis.com/storybox-backend.appspot.com/5649391675244544/Screenshot_from_2017-03-16_113338.png"; name = "Story of Foo"; "story_key" = ahJlfnN0b3J5Ym94LWJhY2tlbmRyEgsSBVN0b3J5GICAgID4woQKDA; } ); }
  • 尝试打印 responsedict["stories"] 以确保您在 swift 中的响应中有多个值
  • 邮递员中的请求是否与您代码中的请求完全相同?
  • responsedict["stories"] prints ( { "image_url" = "http://storage.googleapis.com/storybox-backend.appspot.com/5649391675244544/Screenshot_from_2017-03-16_113338.png"; name = "Story of Foo"; "story_key" = ahJlfnN0b3J5Ym94LWJhY2tlbmRyEgsSBVN0b3J5GICAgID4woQKDA; } ) 只包含一个值
  • 您确定该请求与您在 Postman 中的请求完全相同吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多