gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:37:06 25 4
gpt4 key购买 nike

我正在尝试使用 NSJSONSerialization.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 字符串的清晰 View :

{
"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

最佳答案

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

Playground 输出

enter image description here

解决方案

有时 Xcode Debugger 会出错,所以请尝试记录您的响应,如果调试器无法正常工作,这是最正确的方法

关于swift - 将 API 响应转换为 JSON 对象的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35820158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com