【问题标题】:Swift 5 - Display nested JSON with Arrays of ObjectsSwift 5 - 显示带有对象数组的嵌套 JSON
【发布时间】:2020-03-30 07:54:59
【问题描述】:

我正在尝试找出正确的语法(或者我哪里出错了?)以显示返回的多嵌套 json,其中包含包含更多对象的数组。

我可以设法让嵌套对象工作,但在尝试获取数组中的对象时出现错误。

这是我的结构:

import Foundation

struct spaceXLaunch: Codable {
    var flight_number: Int
    var mission_name: String?
    var launch_date_local: String?
    var rocket: rocketResponse
    var launch_site: launchSiteResponse
    var links: linksResponse
    var launch_success: Bool?
    var details: String?
}

extension spaceXLaunch: Identifiable {
    var id: Int { return flight_number }
}

struct rocketResponse: Codable {
    var rocket_name: String
    var rocket_id: String
    var first_stage: firstStageResponse
    var second_stage: secondStageResponse
}

struct firstStageResponse: Codable {
    var cores: [coresResponse]
}

struct coresResponse: Codable {
    var landing_vehicle: String?
    var land_success: Bool?
    var reused: Bool?
    var landing_type: String?
}

struct secondStageResponse: Codable {
    var payloads: [payloadsResponse]
}

struct payloadsResponse: Codable {
    var payload_id: String?
    var payload_type: String?
    var payload_mass_kg: Double?
}

struct launchSiteResponse: Codable {
    var site_name: String
}

struct linksResponse: Codable {
    var missionPatch: String?
    var missionPatchSml: String?

    private enum CodingKeys: String, CodingKey {
        case missionPatch = "mission_patch"
        case missionPatchSml = "mission_patch_small"
    }
}

这是我用来渲染视图的 SwiftUI 代码

import SwiftUI

struct listView: View {

    @ObservedObject var fetcher = LaunchDataFetcher()

    var body: some View {
        List(fetcher.launches) { spaceXLaunch in

            VStack (alignment: .leading) {

                Text(spaceXLaunch.mission_name ?? "No Data Found")
                Spacer()

                Text(spaceXLaunch.details ?? "No Data Found")
                    .font(.system(size: 11))
                Spacer()

                Text(spaceXLaunch.launch_date_local ?? "No Data Found")
                Spacer()

                Text(spaceXLaunch.rocket.rocket_name)
                Spacer()

                ///This line below comes back with an error of "Cannot subscript a value of incorrect or ambiguous type"
                Text(spaceXLaunch.rocket.first_stage.cores[0].landing_type)
                Spacer()


            }
        }
    }
}

struct listView_Previews: PreviewProvider {
    static var previews: some View {
        listView()
        .environment(\.colorScheme, .dark)
    }
}

这里是为 api 返回的 Json 数据示例

{
        "flight_number": 24,
        "mission_name": "CRS-7",
        "mission_id": [
            "EE86F74"
        ],
        "launch_year": "2015",
        "launch_date_unix": 1435501260,
        "launch_date_utc": "2015-06-28T14:21:00.000Z",
        "launch_date_local": "2015-06-28T10:21:00-04:00",
        "is_tentative": false,
        "tentative_max_precision": "hour",
        "tbd": false,
        "launch_window": 0,
        "rocket": {
            "rocket_id": "falcon9",
            "rocket_name": "Falcon 9",
            "rocket_type": "v1.1",
            "first_stage": {
                "cores": [
                    {
                        "core_serial": "B1018",
                        "flight": 1,
                        "block": 1,
                        "gridfins": true,
                        "legs": true,
                        "reused": false,
                        "land_success": null,
                        "landing_intent": true,
                        "landing_type": "ASDS",
                        "landing_vehicle": "OCISLY"
                    }
                ]
            },
            "second_stage": {
                "block": 1,
                "payloads": [
                    {
                        "payload_id": "CRS-7",
                        "norad_id": [],
                        "reused": false,
                        "cap_serial": "C109",
                        "customers": [
                            "NASA (CRS)"
                        ],
                        "nationality": "United States",
                        "manufacturer": "SpaceX",
                        "payload_type": "Dragon 1.1",
                        "payload_mass_kg": 2477,
                        "payload_mass_lbs": 5460.9,
                        "orbit": "ISS",
                        "orbit_params": {
                            "reference_system": "geocentric",
                            "regime": "low-earth",
                            "longitude": null,
                            "semi_major_axis_km": null,
                            "eccentricity": null,
                            "periapsis_km": null,
                            "apoapsis_km": null,
                            "inclination_deg": 51.6,
                            "period_min": null,
                            "lifespan_years": null,
                            "epoch": null,
                            "mean_motion": null,
                            "raan": null,
                            "arg_of_pericenter": null,
                            "mean_anomaly": null
                        },
                        "mass_returned_kg": null,
                        "mass_returned_lbs": null,
                        "flight_time_sec": 139,
                        "cargo_manifest": "https://www.nasa.gov/sites/default/files/atoms/files/spacex_crs-7_mission_overview.pdf",
                        "uid": "UerI6qmZTU2Fx2efDFm3QQ=="
                    }
                ]
            },
            "fairings": null
        },
        "ships": [
            "ELSBETH3",
            "GOQUEST",
            "GOSEARCHER"
        ],
        "telemetry": {
            "flight_club": null
        },
        "launch_site": {
            "site_id": "ccafs_slc_40",
            "site_name": "CCAFS SLC 40",
            "site_name_long": "Cape Canaveral Air Force Station Space Launch Complex 40"
        },
        "launch_success": false,
        "launch_failure_details": {
            "time": 139,
            "altitude": 40,
            "reason": "helium tank overpressure lead to the second stage LOX tank explosion"
        },
        "links": {
            "mission_patch": "https://images2.imgbox.com/47/39/stH98Qy1_o.png",
            "mission_patch_small": "https://images2.imgbox.com/d0/22/gyTVYo21_o.png",
            "reddit_campaign": null,
            "reddit_launch": "https://www.reddit.com/r/spacex/comments/3b27hk",
            "reddit_recovery": null,
            "reddit_media": "https://www.reddit.com/r/spacex/comments/3berj3",
            "presskit": "https://www.nasa.gov/sites/default/files/atoms/files/spacex_nasa_crs-7_presskit.pdf",
            "article_link": "https://spaceflightnow.com/2015/06/28/falcon-9-rocket-destroyed-in-launch-mishap/",
            "wikipedia": "https://en.wikipedia.org/wiki/SpaceX_CRS-7",
            "video_link": "https://www.youtube.com/watch?v=PuNymhcTtSQ",
            "youtube_id": "PuNymhcTtSQ",
            "flickr_images": [
                "https://farm1.staticflickr.com/344/19045370790_f20f29cd8d_o.jpg",
                "https://farm1.staticflickr.com/287/18999110808_6e153fed64_o.jpg"
            ]
        },
        "details": "Launch performance was nominal until an overpressure incident in the second-stage LOX tank, leading to vehicle breakup at T+150 seconds. The Dragon capsule survived the explosion but was lost upon splashdown because its software did not contain provisions for parachute deployment on launch vehicle failure.",
        "upcoming": false,
        "static_fire_date_utc": "2015-06-26T05:00:00.000Z",
        "static_fire_date_unix": 1435294800,
        "timeline": {
            "webcast_liftoff": 61,
            "go_for_prop_loading": -2280,
            "rp1_loading": -2100,
            "stage1_lox_loading": -2100,
            "stage2_lox_loading": -960,
            "engine_chill": -420,
            "prelaunch_checks": -60,
            "propellant_pressurization": -60,
            "go_for_launch": -45,
            "ignition": -3,
            "liftoff": 0,
            "maxq": 60,
            "meco": 180,
            "stage_sep": 180,
            "second_stage_ignition": 180,
            "seco-1": 540,
            "dragon_separation": 600,
            "dragon_solar_deploy": 720,
            "dragon_bay_door_deploy": 8400
        },
        "crew": null
    },

【问题讨论】:

  • 尝试添加?? "" 在错误行中,因为它也是可选的

标签: arrays json xcode swiftui swift5


【解决方案1】:

感谢 Chris 指出在此行末尾添加可选 (??)

Text(spaceXLaunch.rocket.first_stage.cores[0].landing_type)

所以它看起来像这样:

Text(spaceXLaunch.rocket.first_stage.cores[0].landing_type ?? "No Data Found")

一切正常。

【讨论】:

    【解决方案2】:

    使用以下工具 https://app.quicktype.io 生成您的 JSONModel 结构。然后验证你的逻辑。

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      相关资源
      最近更新 更多