我目前正在向Microsoft的Emotion API发送请求,请求成功,但收到无效JSON
,(无法使用NSJSONSerialization.JSONObjectWithData as! [String: String]
或{转换JSON {1}}但可以转换为SwiftyJSON
(我可以使用NSArray
)。(所有其他选项返回NSArray
)
请求
nil
感兴趣的JSON(来自API测试控制台的结果)
let params = [ "url": "http://reneemullingslewis.com/wp-content/uploads/2014/08/woman-smiling.png" ]
let body = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
let url = NSURL(string: "https://api.projectoxford.ai/emotion/v1.0/recognize")!
let request = NSMutableURLRequest(URL: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("XXXXXXXXXXXXXXXXXXXXXX", forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
request.HTTPBody = body
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray
let dResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:String]
let json = JSON(data!)
print(result)
print(result?[0]["scores"]??["anger"]) //Is works
print(dResult) //Returns nil
print(json) //Returns 'unknown'
} catch {
print(error)
}
}
task.resume()
NSArray结果
[
{
"faceRectangle": {
"height": 208,
"left": 172,
"top": 128,
"width": 208
},
"scores": {
"anger": 2.46091458E-05,
"contempt": 0.297730684,
"disgust": 9.475541E-05,
"fear": 1.13360545E-06,
"happiness": 0.564267159,
"neutral": 0.131727561,
"sadness": 1.14351078E-05,
"surprise": 0.0061426633
}
}
]
答案 0 :(得分:3)
[String:String]
(又名Dictionary<String,String>
)是一个字典,而不是一个数组,JSON的常见Swift数组类型是[[String:AnyObject]]
(又名Array<Dictionary<String,AnyObject>>
)