[英]Swift - Parse JSON using Alamofire from PHP data
我正在嘗試使用PHP為中國用戶創建適配器以連接GoogleAPI。 在json響應中,我試圖獲取描述數據。 但是,我什至無法獲得字典數據。 有什么建議么?
iOS代碼
Alamofire.request(requestString, method: .post, parameters: data, encoding: URLEncoding.httpBody, headers: [:]).responseJSON { (response) in
switch response.result {
case .success(_):
print(response.result.value)
if let dictionary = response.result.value as? Dictionary<String,Any>{
print("dictionary", dictionary)
}
}
}
的PHP
<?php
$post_data = $_POST['data'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://vision.googleapis.com/v1/images:annotate?key=KKEEYY");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-length: ".strlen($post_data)));
$result = curl_exec($ch);
echo json_encode($result);
?>
編輯
如果使用我自己的適配器,我可以看到鍵和值還有額外的“”
如果直接向Google print("direct", response.result.value)
請求print("direct", response.result.value)
如果使用我的適配器print("using adapter", response.result.value)
您的結果已經是字典,無需使用NSDictionary進行轉換。 另外,您必須使用swift類避免在Swift中使用Objective-c類:
試試這個:
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)") // serialized json response
if let responses = jsonDict["responses"] as? [[String:Any]] {
print("3", responses)
}
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
print(error)
break
}
}
希望這會有所幫助..
let jsonData = response.data
let dictionary = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [String : Any]
print("dictionary", dictionary)
為了使它更容易,如果您使用快速JSON並將其與alamofire結合使用,則更好
這是答案。 我知道這太亂了。
if let dictionary = response.result.value as? String {
let data: NSData = dictionary.data(using: String.Encoding.utf8)! as NSData
let json = JSON(data)
let responses = json["responses"].arrayObject
if let resp = responses!.first {
let type = resp as! [String: Any]
if let labelAnnotations = type["labelAnnotations"] as? NSArray {
for labelAnnotation in labelAnnotations {
if let results = labelAnnotation as? NSDictionary {
let description = results["description"] as? String
let score = results["score"] as? Double
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.