打印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, 请持续关注后续版本。 |