Расшифровка вложенного JSON в Swift - PullRequest
0 голосов
/ 17 июня 2019

Я пытаюсь декодировать вложенный JSON. Все значения отображаются в ноль. Может кто-нибудь, пожалуйста, помогите мне с этим.

struct CarouselListings: Decodable {

var success: Bool
var elapsed: Int = 0
let result: Result

struct Result: Decodable {
    let properties: [Property]?
    let neighborhoods: [Neighborhood]?
    let buildings: [Building]?
    let communities: [Community]?
}
    struct Property: Decodable {

    var id:Int?
    var updateTimestamp : String?
    var name : String?
    var description : String?

    struct PropertyType: Codable {
        var id:Int?
        var name = ""
        var description = ""

    }

    var latitude: String?
    var longitude: String?
    var thumbnailImage: String?
    var buildingId: Int?
    var communityId: Int?
    var neighborhoodId: Int64?
    var mint: Bool?
    var active: Bool?

 }

struct Neighborhood: Codable {

}


struct Building: Codable {

}

struct Community: Codable {

}

Пересмотрен как я пропустил 1 уровень

struct CarouselListings: Decodable {

var success: Bool
var elapsed: Int = 0
let result: Result

struct Result: Decodable {
    let properties: [Propertu]?
    let neighborhoods: [Neighborhood]?
    let buildings: [Building]?
    let communities: [Community]?
}

struct Properties: Decodable {
    let propertyDetail: Property?
    let images = [String]()
}
struct Neighborhoods: Decodable {
    let neighborhoodDetails: Neighborhood]?
}
struct Buildings: Decodable {
    let buildingDetail: Building?
}
struct Communities: Decodable {
    let communitieDetail: Community?
}
    struct Property: Decodable {

    var id:Int?
    var updateTimestamp : String?
    var name : String?
    var description : String?

    struct PropertyType: Codable {
        var id:Int?
        var name = ""
        var description = ""

    }

    var latitude: String?
    var longitude: String?
    var thumbnailImage: String?
    var buildingId: Int?
    var communityId: Int?
    var neighborhoodId: Int64?
    var mint: Bool?
    var active: Bool?

 }

struct Neighborhood: Codable {


}


struct Building: Codable {


}

struct Community: Codable {


    }
}

JSON Response

"success": true,
"elapsed": 20,
"result": {
    "neighborhoods": null,
    "properties": [
        {
            "property": {
                "id": 1,
                "updateTimestamp": null,
                "name": "Al Deyar",
                "description": "Al Deyar Villa",
                "propertyType": {
                    "id": 709415277471,
                    "name": "villa",
                    "description": "villa"
                },
                "latitude": "1",
                "longitude": "2",
                "thumbnailImage": "https://q-ak.bstatic.com/images/hotel/max1280x900/167/167547890.jpg",
                "video": null,
                "buildingId": 1,
                "communityId": 1,
                "neighborhoodId": 1634048588303324,
                "mint": true,
                "active": true
            },
            "images": []
        }
    ],
    "buildings": null,
    "communities": null
  } 
}

Вот как я звоню

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

                    guard let data = data else {
                        return
                    }
                    do {
                        let decoder = JSONDecoder()

                        let response = try decoder.decode(CarouselListings.self, from: data)
                        print(response)
                        if let properties = response.result.properties {
                            successBlock(properties,response.success)
                         }
                    } catch let error {
                        errorBlock(error)
                    }
                    }.resume()

Ответы [ 2 ]

2 голосов
/ 17 июня 2019

Вы пропустили уровень. Ваш тип Property должен иметь свойство property, значение которого, скажем, PropertyDetail. В PropertyDetail именно туда нужно перейти id, updateTimestamp и т. Д.

Так, например:

struct CarouselListings: Decodable {
    var success: Bool
    var elapsed: Int = 0
    let result: Result
    struct Result: Decodable {
        let properties: [Property]?
    }
    struct Property: Decodable {
        let property: PropertyDetail?
    }
    struct PropertyDetail: Decodable {
        var id:Int?
        var updateTimestamp : String?
        var name : String?
        var description : String?
        // and so on
    }
}
0 голосов
/ 17 июня 2019

Ваш код декодирования правильный, у вас, вероятно, есть имя, отличное от вашего результата json.

вставь! после того, как вы попытаетесь заставить ваш код вызвать сбой, он покажет, какое свойство неверно.

let response = try! decoder.decode(CarouselListings.Property.self, from: data)
...