2017-09-16 2 views
3

누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까? 여기에서 모든 질문을 여기에서 보았습니다. How to decode a nested JSON struct with Swift Decodable protocol?과 내가 정확히 필요한 것인가를 발견했습니다. Swift 4 Codable decoding json.스위프트 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