在Swift

时间:2019-06-05 18:19:51

标签: json swift codable decoder

我能够从端点检索一些JSON,但是当我尝试将该JSON解码为模型对象时,无法解析JSON出现了问题。我已经确保模型对象中的属性与json键匹配,所以我不明白问题出在哪里。每次都会打印出catch块。

这是我检索json的代码:

func getServiceProviders() {
    let session = URLSession.shared

    let url = URL(string: "http://exampleendpoint.com/example")!

    URLSession.shared.dataTask(with: url) { data, response, error in



 //Here is where I try to decode the json into my model object

            do {
            let jsonContent = try JSONDecoder().decode(ServiceObject.self, from: data!)
            print(jsonContent)
        } catch {
            print("Ooops")
        }


}.resume()

这是我的模型对象:

     struct ServiceObject: Decodable {
let serviceproviders: [ServiceProvider]



struct ServiceProvider: Decodable {
let city: String
let coordinates: Location
let name: String
let overallGrade: String
let postalCode: Int
let state: String
let reviewCount: Int
 }

 struct Location: Decodable {
let latitude: Double
let longitude: Double
 }

 }

这是我检索到的json对象的样子:

      {
"serviceproviders": [
    {
    "city" : "Beech Grove",
    "coordinates" :                 {
        "latitude" : "39.715417",
        "longitude" : "-86.095646"
    },
    "name" : "William J Ciriello Plumbing Co Inc",
    "overallGrade" : "A",
    "postalCode" : "46107",
    "state" : "Indiana",
    "reviewCount" : 309
},
            {
    "city" : "Indianapolis",
    "coordinates" :                 {
        "latitude" : "39.922607",
        "longitude" : "-86.0267094"
    },
    "name" : "Roby's Plumbing & Appliance Service",
    "overallGrade" : "B",
    "postalCode" : "46256",
    "state" : "Indiana",
    "reviewCount" : 903
},

0 个答案:

没有答案