現在SwiftでPOST通信を行い、jsonで値を取得しようとしているのですが、「Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0.」というエラーが出て値を取得できません。
Swift
1let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in 2 if error == nil { 3 print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)) 4 do { 5 let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: String] 6 print(jsonResult) 7 } catch { 8 print("jsonError: \(error)") 9 } 10
上記のコードの
Swift
1print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
で値は以下のように出力されています。
Optional(array(30) {
[0]=>
array(1) {
["名詞"]=>
string(6) "電車"
}
[1]=>
array(1) {
["名詞"]=>
string(15) "コンセント"
}
.
.
.
}
ここからJSONSerialization.jsonObjectでパースするにはどのようにすればいいでしょうか?
どなたかわかる方がいれば教えていただきたいです。よろしくお願いします。
///追記///
print(jsonResult)は通ってないので何も出力がされてないです。「as! [String: String]」を削除して、あれから少しphp側もいじるとprint(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))では
string(1153) "[{"\u540d\u8a5e":"\u30cf\u30b5\u30df"},{"\u540d\u8a5e":"\u30d2\u30e8\u30b3"},..........]
という出力結果になりましたが、結局try JSONSerialization.jsonObjectで「Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.」のエラーが返ってきます......。
///追記///
以下はphp側の処理になります。
php
1class DBHelper { 2 3 public function getDataFromDB() { 4 try { 5 $pdo = new PDO($dsn, $username, $password); 6 $stmt = $pdo->prepare('SELECT * FROM word WHERE speech = ?'); 7 $stmt->bindValue(1, $this->getSpeechFromClient()); 8 $stmt->execute(); 9 $results = $stmt->fetchAll(); 10 11 } catch (PDOException $e) { 12 return NULL; 13 } 14 15 $distinctWords = $this->removeDuplication($this->getWordFromClient(), $results); 16 17 return $distinctWords; 18 } 19 20 public function getSpeechFromClient() { 21 $json_string = file_get_contents('php://input'); 22 $obj = json_decode($json_string, true); 23 24 return $obj['speech']; 25 } 26 27 public function getWordFromClient() { 28 $clientWord = array(); 29 30 $json_string = file_get_contents('php://input'); 31 $obj = json_decode($json_string, true); 32 33 foreach($obj['words'] as $value) { 34 array_push($clientWord, $value); 35 } 36 37 return $clientWord; 38 } 39 40 public function removeDuplication($clientData, $serverData) { 41 $serverData = array_diff($serverData, $clientData); 42 shuffle($serverData); 43 44 $data = array(); 45 $speech = $this->getSpeechFromClient(); 46 47 if (count($serverData) >= 30) { 48 for ($i = 0; $i < 30; $i++) { 49 $data += [$speech => $serverData[$i]['word']]; 50 } 51 return $data; 52 53 } else { 54 return NULL; 55 } 56 } 57} 58 59///main/// 60 61$dbhelper = new DBHelper(); 62$words = $dbhelper->getDataFromDB(); 63$jsonWords = json_encode($words); 64 65echo $jsonWords; 66 67?>
回答2件
あなたの回答
tips
プレビュー