设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

如何在Swift中优雅地处理JSON

2014-7-22 12:35| 发布者: joejoe0332| 查看: 4048| 评论: 0|原作者: 无若, 地狱星星, 徐继开|来自: OSCHINA

摘要: 因为Swift对于类型有非常严格的控制,它在处理JSON时是挺麻烦的,因为它天生就是隐式类型。SwiftyJSON是一个能帮助我们在Swift中使用JSON的开源类库。开始之前,让我们先看一下在Swift中处理JSON是多么痛苦。 ...


打印

JSONValue遵守Printable协议.所以很容易在原始字符串中得到JSON数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let json = JSONValue(dataFromNetwork)
println(json)
/*You can get a well printed human readable raw JSON string:
      {
        "url": {
          "urls": [
            {
              "expanded_url": null,
              "url""http://bit.ly/oauth-dancer",
              "indices": [
                0,
                26
              ],
              "display_url": null
            }
          ]
       }
*/

如果你不想打印出来,你可以使用.description属性来得到上述字符串。

1
let printableString = json.description

调试与错误处理

要是JSON数据出错或者我们错误地检索数据,那会怎么样呢?你可以使用if语句来测试:

1
2
3
4
let json = JSONValue(dataFromNetworking)["some_key"]["some_wrong_key"]["wrong_name"]
if json{
  //JSONValue it self conforms to Protocol "LogicValue", with JSONValue.JInvalid stands for false and others stands true
}

如果我们尝试使用错误的键值或索引来访问数据,description属性会高数你KeyPath在哪里出错了.

1
2
3
4
5
6
7
8
9
10
11
12
let json = JSONValue(dataFromNetworking)["some_key"]["some_wrong_key"]["wrong_name"]
if json{
 
else {
  println(json)
  //> JSON Keypath Error: Incorrect Keypath "some_wrong_key/wrong_name"
  //It always tells you where your key went wrong
  switch json{
  case .JInvalid(let error):
    //An NSError containing detailed error information 
  }
}


后记

   SwiftyJSON的开发将会发布在Github, 请持续关注后续版本。


酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部