将API响应转换为JSON对象的问题

时间:2016-03-05 21:32:31

标签: swift nsjsonserialization

我正在尝试使用NSJSONSeriallization.JSONObjectWithData将NSData转换为JSON对象,我当前的代码是:

let response = try! NSJSONSerialization.JSONObjectWithData(receivedData, options: .MutableContainers) as! [String:AnyObject]

var receivedData是1013个字节,包含来自API的JSON响应。

如果将我的NSData响应转换为使用此行代码而不是上一行的字符串:

let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)

使用Xcode调试我们可以看到response作为字符串是: enter image description here

这是一个更清晰的JSON字符串视图:

{
  "id": "373198",
  "result": {
    "registrationId": 742098068,
    "imageUrl": "/templates/images/user.gif",
    "external": false,
    "clientCode": "",
    "settings": null,
    "firstLogin": false,
    "type": null,
    "fromSite": null,
    "city": "",
    "sessionToken": "1457206061819919",
    "username": "buffettidemo",
    "postalCode": null,
    "phoneNumber": "",
    "permissions": null,
    "role": null,
    "gender": "",
    "specialBonus": null,
    "verifyPhone": null,
    "autocashout": null,
    "wizardFlags": 1,
    "lastName": "Demo",
    "enableMail": true,
    "extType": null,
    "companyName": null,
    "extId": null,
    "country": "",
    "paypalAccountEmail": null,
    "console": 2,
    "authorizationProfile": null,
    "thumbnail": null,
    "email": "adriano.tamburo@gmail.com21",
    "javaClass": "guardian.dto.UserAdaptor",
    "language": null,
    "numInvitation": 0,
    "region": null,
    "enablePhone": true,
    "registerDate": "1426693995000",
    "verifyMail": null,
    "id": 80447,
    "firstName": "Buffetti",
    "salesFee": null,
    "website": null,
    "dateBirth": "1426693995000",
    "taxCode": null,
    "quotesOrders": null,
    "permissionApp": null,
    "address": null,
    "authorizationExpired": false,
    "vatNumber": null,
    "mobileNumber": null
  }
}

我的问题是,回到使用这行代码:

let response = try! NSJSONSerialization.JSONObjectWithData(receivedData, options: .MutableContainers) as! [String:AnyObject]

我的词典对象[string:AnyObject]没有条目:

enter image description here

1 个答案:

答案 0 :(得分:0)

通过抓取您的回复并将其放入文件并将其加载到 Playground 进行简单测试,似乎可行。而且我也没有注意到您的回复有任何问题,因为我还使用 JSON Validator 对其进行了验证。

游乐场输出

enter image description here

解决方案

有时 Xcode Debugger 搞砸了,所以如果调试器不能正常工作,请尝试记录您的响应,这是最正确的方法