2017-09-16 7 views
3

誰かが間違っていることを教えてもらえますか?私はここですべての質問を見てきましたHow to decode a nested JSON struct with Swift Decodable protocol?と私は正確に私が必要と思われるものを見つけましたSwift 4 Codable decoding jsonSwift 4コーディング可能なjsonを使用する

{ 
"success": true, 
"message": "got the locations!", 
"data": { 
    "LocationList": [ 
     { 
      "LocID": 1, 
      "LocName": "Downtown" 
     }, 
     { 
      "LocID": 2, 
      "LocName": "Uptown" 
     }, 
     { 
      "LocID": 3, 
      "LocName": "Midtown" 
     } 
    ] 
    } 
} 

struct Location: Codable { 
    var data: [LocationList] 
} 

struct LocationList: Codable { 
    var LocID: Int! 
    var LocName: String! 
} 

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let url = URL(string: "/getlocationlist") 

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in 
     guard error == nil else { 
      print(error!) 
      return 
     } 
     guard let data = data else { 
      print("Data is empty") 
      return 
     } 

     do { 
      let locList = try JSONDecoder().decode(Location.self, from: data) 
      print(locList) 
     } catch let error { 
      print(error) 
     } 
    } 

    task.resume() 
} 

私は取得していますエラーは次のとおりです。

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

答えて

5

があなたのJSONテキストの概略構成チェック:"data"の値はJSONオブジェクト{...}がある

{ 
    "success": true, 
    "message": "got the locations!", 
    "data": { 
     ... 
    } 
} 

を、そうではありません配列。 物体の構造:

{ 
    "LocationList": [ 
     ... 
    ] 
} 

オブジェクトが単一のエントリ"LocationList": [...]を有し、その値は配列[...]あります。

あなたはもう一つの構造体が必要になる場合があります

テストでは
struct Location: Codable { 
    var data: LocationData 
} 

struct LocationData: Codable { 
    var LocationList: [LocationItem] 
} 

struct LocationItem: Codable { 
    var LocID: Int! 
    var LocName: String! 
} 

...

var jsonText = """ 
{ 
    "success": true, 
    "message": "got the locations!", 
    "data": { 
     "LocationList": [ 
      { 
       "LocID": 1, 
       "LocName": "Downtown" 
      }, 
      { 
       "LocID": 2, 
       "LocName": "Uptown" 
      }, 
      { 
       "LocID": 3, 
       "LocName": "Midtown" 
      } 
     ] 
    } 
} 
""" 

let data = jsonText.data(using: .utf8)! 
do { 
    let locList = try JSONDecoder().decode(Location.self, from: data) 
    print(locList) 
} catch let error { 
    print(error) 
} 
+0

ああ、当たり前!それをキャッチするためにありがとう。 – Misha

関連する問題