简体   繁体   中英

Return specific object in JSON array using swift

Using a struct I am getting data from JSON via a web API and I would like to print all of the data for a specific object eg I would like to print all Product Id's from the response.

Here is my code:

    struct Varients: Decodable {
    let ProductId: String
    let Colour: String
    let name: String
}

struct varientsResponse: Decodable {
    let varients: [Varients]
}

View Controller:

let url = URL(string: "http://192.168.1.113:8000/getvarient/?url=https://www.prettylittlething.com/stone-abstract-marble-print-structured-corset.html")
    guard let requestUrl = url else { fatalError() }
    // Create URL Request
    var request = URLRequest(url: requestUrl)
    // Specify HTTP Method to use
    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        
        // Check if Error took place
        if let error = error {
            print("Error took place \(error)")
            return
        }
        
        // Read HTTP Response Status code
        if let response = response as? HTTPURLResponse {
            print("Response HTTP Status code: \(response.statusCode)")
        }
        
        // Convert HTTP Response Data to a simple String
        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            let varientResponse = try? JSONDecoder().decode(varientsResponse.self, from: data)
            print(varientResponse)
            
            
       
        }
        
    }
    task.resume()

JSON Response Example:

  "varients": [
    {
      "ProductId": "1703412",
      "Colour": "Stone",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/2/7/f/4/27f4825ee181668f1e8e5797478607b505dbee1c_cmt4421_1.jpg?imwidth=1024",
      "name": "Stone  Abstract Marble Print Structured Corset"
    },
    {
      "ProductId": "865801",
      "Colour": "Pastel Orange",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/e/b/e/6/ebe60bba9afe0fc20fabbb5db34494dcd688dc4b_CMF1440_1.jpg?imwidth=1024",
      "name": "Orange Tie Dye Print Structured Corset Top"
    },
    {
      "ProductId": "867743",
      "Colour": "Purple",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/d/a/8/3/da83149d0c6e00e094e417f3ed2d4b15927d15a9_CMF1829_1.jpg?imwidth=1024",
      "name": "Purple Tie Dye Print Structured Corset Top"
    },
    {
      "ProductId": "979950",
      "Colour": "Fuchsia",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/a/0/e/2/a0e2d0847f64ee961388272009203461ee7028ee_cmg7868_1.jpg?imwidth=1024",
      "name": "Fuschia Tie Dye Print Structured Corset Top"
    },
    {
      "ProductId": "1083745",
      "Colour": "Acid Blue Wash",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/b/e/7/4/be744c7f8fef860182ea730572c3f1dfb8b4820e_cmk5407_1.jpg?imwidth=1024",
      "name": "Blue Tie Dye Print Structured Corset Top"
    },
    {
      "ProductId": "1083753",
      "Colour": "Light Pink",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/f/c/8/7/fc8700bbd28684d418f4ed49b638bda9112b1aca_cmk5405_1.jpg?imwidth=1024",
      "name": "Light Pink Tie Dye Print Structured Corset Top"
    },
    {
      "ProductId": "1450163",
      "Colour": "Turquoise",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/6/6/6/f/666fc73c32602aa964f69d65fee2e3f77198448d_cmp4910_1.jpg?imwidth=1024",
      "name": "Turquoise Marble Print Structured Corset Top"
    },
    {
      "ProductId": "1667090",
      "Colour": "Pink",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/f/8/a/8/f8a85d97fe670e37ec5903d435e1ac44ecad8fd7_cms8800_1.jpg?imwidth=1024",
      "name": "Pink Abstract Renaissance Print Structured Corset"
    },
    {
      "ProductId": "1698866",
      "Colour": "Monochrome",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/f/7/a/a/f7aa8247197d6dcfc8f8bd270d7b50626e857d62_cmt3674_1.jpg?imwidth=1024",
      "name": "Black Zebra Print Structured Corset Top"
    },
    {
      "ProductId": "1703508",
      "Colour": "Green",
      "Sizes": [
        "4",
        "6",
        "8",
        "10",
        "12",
        "14",
        "16"
      ],
      "image": "https://cdn-img.prettylittlething.com/c/b/d/f/cbdf70eaa970a1ffaa3f3b54e9b7c4173ee0c560_cmt4422_1.jpg?imwidth=1024",
      "name": "Green  Abstract Marble Print Structured Corset"
    }
  ]
}

I can return the varientsResponse but I obviously get the full JSON response, I can also return the varientsResponse.varients[0].productId but I would like to be able to get a full array of all productID's in the JSON

To answer your initial question and then also your follow up question in the comments.

You can access the Colour and the ID for a specific item like this:

varientResponse.variants.map { varient in 
  
  // Save to database by accessing like this:
  // Colour - varient.Colour
  // ID - varient.ProductID

}

Unrelated to your question, but normally Structs are named as singular. Which makes sense as each instance of your struct will be a singular Varient .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM