gpt4 book ai didi

ios - 在我的 swift 应用程序中将 NSData 解析为 Json 失败

转载 作者:行者123 更新时间:2023-11-29 00:58:14 25 4
gpt4 key购买 nike

我通过以下代码从在线 API 获取了 NSData:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("\(error)")
return
}
let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("\(res)")
};
task.resume()

数据看起来像这样(NSString 没问题):

{
"word": "detrimental",
"results": [
{
"definition": "(sometimes followed by `to') causing harm or injury",
"partOfSpeech": "adjective",
"synonyms": [
"damaging",
"prejudicial",
"prejudicious"
],
"similarTo": [
"harmful"
],
"derivation": [
"detriment"
]
}
],
"syllables": {
"count": 4,
"list": [
"det",
"ri",
"men",
"tal"
]
},
"pronunciation": {
"all": ",dɛtrə'mɛntəl"
},
"frequency": 2.77
}

现在,我正在尝试将数据解析为 json。我尝试了一些方法但都失败了。就像这个:

func getJSON(data:NSData) -> [[String:AnyObject]]{
var json = [[String:AnyObject]]()
do {
json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [[String:AnyObject]]
} catch {}
return json;
}

这个也失败了:(原因:无法将类型“__NSCFDictionary”(0xd755c0)的值转换为“NSArray”(0xd752f0)。)

func hiJson(data:NSData) -> NSArray {
var json: NSArray!
do {
json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSArray
} catch {
print(error)
}
return json
}

有人能帮忙吗?

最佳答案

我确定它不是一个数组,它是一个字典。像这样解析为 Json:

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSDictionary

要获取定义键,请执行此操作

res.valueForKeyPath("results.definition")

关于ios - 在我的 swift 应用程序中将 NSData 解析为 Json 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366858/

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