【问题标题】:Return specific object in JSON array using swift使用 swift 返回 JSON 数组中的特定对象
【发布时间】:2021-10-17 21:13:34
【问题描述】:

使用结构,我通过 Web API 从 JSON 获取数据,我想打印特定对象的所有数据,例如,我想打印响应中的所有产品 ID。

这是我的代码:

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

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

视图控制器:

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 响应示例:

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

我可以返回 varientsResponse 但我显然得到了完整的 JSON 响应,我也可以返回 varientsResponse.varients[0].productId 但我希望能够得到 JSON 中所有 productID 的完整数组

【问题讨论】:

  • print(varientResponse.variants.map(\.ProductId))
  • 完美,现在可以工作了,我如何将 productID 映射到颜色?基本上,我在下拉列表中显示颜色,一旦用户做出选择,它会将其保存到数据库中,但我还需要保存该颜色选择的产品 ID。

标签: ios json swift


【解决方案1】:

回答您最初的问题,然后回答您在 cmets 中的后续问题。

您可以像这样访问特定项目的颜色和 ID:

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

}

与您的问题无关,但通常将结构命名为单数。这是有道理的,因为您的结构的每个实例都是一个单数 Varient

【讨论】:

  • 感谢您的回复 Joshua,我是否认为我可以使用 vairentResponse.variants.map { } 将 productId 映射到颜色?
  • 是的,你甚至可以使用你已经存在的结构体,在地图中类似let myVarient = Varient(ProductId: varient.ProductId, Color: varient.Color, Name: varient.name),然后发送你的数据库myVarient。如果您想一次发送多个变体,您可以考虑将 Varient 实例推送到 Varient 数组并将其发送到后端。
  • 当我打印时:让 myVarient = (varientNew.Colour + " " + "((varientNew.ProductId))") 它显示产品的两个变体,但是当我在应用程序上显示它时用户作为数组我只得到一个产品
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多