无法解析json响应swift

时间:2015-04-03 23:06:09

标签: ios json swift

jsonResponse有两个键,它的值不是实际值。

代码:

var responseDictionary = jsonResponse as Dictionary<String, AnyObject>
var statusDictionary = responseDictionary["status"] as Array<AnyObject>

statusDictionary的结果

2 values
 {
  [0] = <error: use of undeclared identifier 'cocoarr'
error: 1 errors parsing expression
>

  [1] = <error: use of undeclared identifier 'cocoarr'
error: 1 errors parsing expression
>

responseDictionary的结果:

(lldb) po responseDictionary
 {
  [0] = {
    key = "status"
    value = (instance_type = Builtin.RawPointer = 0x00007fbb13dd0ee0 -> 0x0000000106aaf380 (void *)0x0000000106aaf3a8: __NSCFArray)
  }
  [1] = {
    key = "lastRunTime"
    value = (instance_type = Builtin.RawPointer = 0x00007fbb13dd0f70 -> 0x0000000106aae980 (void *)0x0000000106aae930: __NSCFString)
  }
}

哪些结果无法解析值。

如果我做“po println(responseDictionary)”。我可以看到正确的结果。 解析有什么问题?

由于

1 个答案:

答案 0 :(得分:1)

Swift编程语言书中说

  

“仅当您确定向下转换将始终成功时,才使用类型转换运算符的强制形式(as)。如果您尝试向下转换为不正确的类类型,则此形式的运算符将触发运行时错误。“

摘自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itun.es/us/jEUH0.l

当您解析JSON并将其转换为本机Swift对象时,您不应该对JSON的结构做任何假设。您应该使用类型转换操作符的更安全的形式,即可选形式。

在反序列化JSON时,使用单元测试(或Playground)是一个很好的起点。请参阅下面的样本单元测试。

    func testExample() {
        var jsonString  = "{" +
        "\"lastRunTime\" : \"2004-05-06T14:13:55\"," +
        "\"status\" : [" +
        "\"finished\"," +
        "\"processed\"" +
        "]" +
    "}";

        var jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true);
        XCTAssertNotNil(jsonData);

        if let jsonDataObject : NSData = jsonData {
            var error : NSError?;
            let options : NSJSONReadingOptions = NSJSONReadingOptions();

            var deserializedJson : AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonDataObject, options: options, error: &error);

            XCTAssertNil(error);
            if nil == error {
                if let jsonDictionary = deserializedJson as? NSDictionary {
                    if let statusArray = jsonDictionary["status"] as? NSArray {
                        if let firstStatus = statusArray.firstObject as? String {
                            print(firstStatus);

                        }
                        else {
                            XCTFail("the status array should contain strings");
                        }
                    }
                    else {
                        XCTFail("the json dictionary should contain a property whose name is status and whose value is an array");
                    }
                }
                else {
                    XCTFail("json should have been deserialized to a dictionary at the highest level");
                }
            }
        }

    }

另外,在使用Swift时,不要过分依赖调试器。它不像Objective-C那样干净地报告对象值。