2016-10-03 30 views
-2

私はswift2.2用のjson構文解析コードを使用していますが、Swift 3.0用に使用するとエラーが発生します(タイプ'Any'には添字のメンバーはありません)。コード。タイプ'Any 'には添え字がありません

do {   
       let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) 

       if json is [String: AnyObject] { 
        print(json) 

        if let error = json["error"] as? String { 
         print(error); 
        } else if let items = json["items"] as? [[String: AnyObject]] { 

         for item in items { 
          print(item) 

          let book_id = item["id"] as? String 

          if let volumeInfo = item["volumeInfo"] as? [String: AnyObject] { 
           let book_title = volumeInfo["title"] as? String 
           DispatchQueue.main.async(execute: {() -> Void in 
            self.lblDataInfo.text = "ISBN: "+self.currentISBN!+" ID:"+book_id! 
            self.lblDataType.text = book_title 
           }) 
          } 

          break // for now, only show first 
         } 

        } else { 
         DispatchQueue.main.async(execute: {() -> Void in 
          self.lblDataInfo.text = "ISBN: "+self.currentISBN!+" Not identified" 
          self.lblDataType.text = "" 
         }) 
        } 
       } 

      } catch let jsonError { 
       print(jsonError) 
      } 

      } 
      task.resume() 

     } 
} 
+2

** Related **の欄には多くの関連する質問があります。 – vadian

答えて

0

この:JSONは辞書ですが、ここで辞書として、それを試してみて、アクセスときに、辞書にキャストしていない場合if json is [String: AnyObject] {がチェックされます。json["error"]あなたのようにそれにアクセスしようとしています辞書。

代わりに、あなただけの正しい型の新しい変数にキャストする必要があります。

if let jsonDictionary = json as? [String : AnyObject] {

-1

JSONデータが伝わってくるかのように思えますが、それはデータがどのような種類を知っていません、今のようにはAny

if json is [String: AnyObject] { 
       print(json) 
let jsonData = json as! NSDictionary // or if you want to be more specific ,'json as! [String: AnyObject]' but u will have to cast the value of your dict 'AnyObject' later on 

今型であるため、データは「任意」が、タイプの「NSDictionaryの」

タイプではありませんテストする場合は、 print(json)行でブレークポイントを設定し、コードを実行した後にコンソールタイプで po json as! NSDictionaryと入力すると、NSDictionaryがjsonデータをキャストする正しいタイプであるかどうかを確認できます
関連する問題