2017-09-16 4 views
3

Kann mir jemand sagen, was ich falsch mache? Ich habe alle Fragen hier von hier aus gesehen How to decode a nested JSON struct with Swift Decodable protocol? und ich habe eine gefunden, die genau das scheint, was ich brauche Swift 4 Codable decoding json.Swift 4 Dekodierung Json mit Codable

{ 
"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() 
} 

Der Fehler, den ich bekommen habe ist:

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

Antwort

5

die skizzierte Struktur Ihrer JSON Text überprüfen:

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

Der Wert für "data" ein JSON-Objekt ist {...}, ist es nicht eine Anordnung. und die Struktur des Objekts:

{ 
    "LocationList": [ 
     ... 
    ] 
} 

Das Objekt hat einen einzigen Eintrag "LocationList": [...] und sein Wert ist ein Array [...].

Sie können eine weitere Struktur brauchen:

struct Location: Codable { 
    var data: LocationData 
} 

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

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

Zum Testen ...

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

Oh, duh! Danke, dass du das verstanden hast. – Misha