簡體   English   中英

使用JSONDecoder和可編碼協議進行聯網

[英]Networking using JSONDecoder & codable protocol

我想知道我做錯了什么。 我試圖了解如何使用JSONDecoder使用urlsession和codable協議。 當我使用JSONDecoder時,我收到以下錯誤消息:

keyNotFound(CodingKeys(stringValue:“name”,intValue:nil),我的resaponse包含''name''。但是當我使用JSONSerialization時,我能夠打印響應。如果有人可以解釋我。

使用JSONDecoder的代碼

struct Business:Codable {
    let name: String
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }

    init(from decoder: Decoder) throws {
        let value = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try value.decode(String.self, forKey:CodingKeys.name)
    }
}

let task = session.dataTask(with: request) { (data, response, error) in
    if let response = response as? HTTPURLResponse {
        print(response)
    } else{
        print("error")
    }

    guard let data = data else {return}

    do {
        let business = try JSONDecoder().decode(Business.self, from: data)
        print(business.name)
    } catch {
        print("Error parsing JSON: \(error)")
    }
}

task.resume()

使用JSONSerialization的代碼

struct Business: Decodable {
    let name: String
    let displayAddress: String
    let categories: String
    let imageUrl : String

    init(json: [String:Any]) {
        name = json["name"] as? String ?? ""
        displayAddress = json["location"] as? String ?? ""
        categories = json["categories"] as? String ?? ""
        imageUrl = json["image_url"] as? String ?? ""
    }
}

let task = session.dataTask(with: request) { (data, response, error) in
    if let response = response as? HTTPURLResponse {
        print(response)
    } else{
        print("error")
    }

    guard let data = data else {return}

    do {
        if let myjson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? Dictionary<String,Any> {
            print(myjson)
        }
    } catch {
        print("Error parsing ")
    }
}

task.resume()

響應

["region": {
    center =     {
        latitude = "43.67428196976998";
        longitude = "-79.39682006835938";
    };
}, "businesses": <__NSArrayM 0x60000211cff0>(
{
    alias = "pai-northern-thai-kitchen-toronto-5";
    categories =     (
                {
            alias = thai;
            title = Thai;
        }
    );
    coordinates =     {
        latitude = "43.647866";
        longitude = "-79.38864150000001";
    };
    "display_phone" = "+1 416-901-4724";
    distance = "3010.095870925626";
    id = "r_BrIgzYcwo1NAuG9dLbpg";
    "image_url" = "https://s3-media3.fl.yelpcdn.com/bphoto/t-g4d_vCAgZH_6pCqjaYWQ/o.jpg";
    "is_closed" = 0;
    location =     {
        address1 = "18 Duncan Street";
        address2 = "";
        address3 = "";
        city = Toronto;
        country = CA;
        "display_address" =         (
            "18 Duncan Street",
            "Toronto, ON M5H 3G8",
            Canada
        );
        state = ON;
        "zip_code" = "M5H 3G8";
    };
    name = "Pai Northern Thai Kitchen";
    phone = "+14169014724";
    price = "$$";
    rating = "4.5";
    "review_count" = 2405;
    transactions =     (
    );
    url = "https://www.yelp.com/biz/pai-northern-thai-kitchen-toronto-5?adjust_creative=A4ydpSOHv8wBNquTDeh0DQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=A4ydpSOHv8wBNquTDeh0DQ";
},

Business不是JSON中的根數據對象。 你需要這樣的東西:

struct Business: Codable {
    let name: String
}

struct RootObject: Codable {
    let businesses: [Business]
}


let rootObject = try JSONDecoder().decode(RootObject.self, from: data)
print(rootObject.businesses.first?.name)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM