1

I am able to show the name, cost per launch, etc of the JSON. However I cannot access the value for payload_weights and flic_images. I think because they are inside an array of objects.

Here is part of the JSON file

[
  {
    "rocketid": 1,
    "id": "falcon1",
    "name": "Falcon 1",
    "type": "rocket",
    "active": false,
    "stages": 2,
    "boosters": 0,
    "cost_per_launch": 6700000,
    "success_rate_pct": 40,
    "first_flight": "2006-03-24",
    "country": "Republic of the Marshall Islands",
    "company": "SpaceX",
    "height": {
      "meters": 22.25,
      "feet": 73
    },
    "diameter": {
      "meters": 1.68,
      "feet": 5.5
    },
    "mass": {
      "kg": 30146,
      "lb": 66460
    },
    "payload_weights": [
      {
        "id": "leo",
        "name": "Low Earth Orbit",
        "kg": 450,
        "lb": 992
      }
    ]

This is my model:

struct Rocket: Codable, Identifiable {
    var id: String
    var name: String
    var type: String
    var active: Bool
    var stages: Int
    var boosters: Int
    var cost_per_launch: Int
    
    struct PayloadWeight: Codable {
        var id: String
        var name: String
        var kg: Int
        var lb: Int
    }
    
    var payload_weights: [PayloadWeight]
}

This is the view I want to show my data.

struct ContentView: View {
    let rockets = Bundle.main.decode([Rocket].self, from: "Rocket.json")
   
    var body: some View {
        List(rockets) { rocket in
            HStack {
                Text(rocket.name)
            }
        }
    }
}

1 Answer 1

1

The payload_weights property is an array. Which means you can either access the first item (if it exists) or display all of them.

You may try the following:

struct ContentView: View {
    let rockets: [Rocket] = Bundle.main.decode([Rocket].self, from: "Rocket.json")
   
    var body: some View {
        List(rockets) { rocket in
            VStack {
                Text(rocket.name)
                List(rocket.payload_weights) { payloadWeight in
                    self.payloadWeightView(payloadWeight: payloadWeight)
                }
            }
        }
    }
    
    func payloadWeightView(payloadWeight: Rocket.PayloadWeight) -> some View {
        Text(payloadWeight.name)
    }
}

Note: you need to conform PayloadWeight to Identifiable as well:

struct PayloadWeight: Codable, Identifiable { ... }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.