在Swift中解码嵌套的JSON

时间:2019-06-17 19:00:10

标签: json swift codable decodable

我正在尝试解码嵌套的JSON。所有值都映射为nil。 有人可以帮我吗

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响应

"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 个答案:

答案 0 :(得分:2)

您已跳过一个级别。您的Property类型需要有一个property属性,其值就是一个PropertyDetail。在PropertyDetail中,这是idupdateTimestamp等需要去的地方。

例如:

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
    }
}

答案 1 :(得分:0)

您的解码代码正确,您的名称可能与json结果不同。

放一个!在“尝试”使您的代码崩溃之后,它将显示wich属性是错误的。

require('dotenv').config();

const {RESTDataSource} = require('apollo-datasource-rest')
import firebaseInitialize from '../../firebase_initialize'

const firebase = firebaseInitialize()

class PlanData extends RESTDataSource {
    constructor() {
        super();
        this.baseURL = 'https://api.com/';
        this.getPlanById = this.getPlanById.bind(this)
    }

    willSendRequest(request) {
        console.log(this.context.headers);
        request.headers.set('Auth', this.context.headers.authorization);
    }

    planReducer(data) {
        return {
            id: data.plan.id,
            image: data.plan.image,
            title: data.plan.title
        }
    }

    getPlanById = async ({planId}) => {
        const parent = this;
        const db = firebase.database();
        const ref = db.ref(`plans/${planId}`);
        return await new Promise((resolve) => {
            ref.once('value', function (snapshot) {
                const data = snapshot.val();
                resolve(parent.planReducer(data));
            }).catch((e) => {
                console.log(e);
                // add some sensible error handling here
                resolve(null);
            });
        });

    }
}