如何在swiftyJSON和Alamofire中获得字典的随机值

问题描述 投票:0回答:1

我想以random顺序获得1(one)“值”,并带有“本地化”“ NL”,而不是whole JSON response.result值。我该怎么做?

示例:

{
    "id": "3",
    "value": "..",
    "localization": "NL"
} 

我有一个带有以下内容的JSON文件:

[{
    "id": "1",
    "value": "..",
    "localization": "NL"
}, {
    "id": "2",
    "value": "..",
    "localization": "NL"
}, {
    "id": "3",
    "value": "..",
    "localization": "NL"
},
{
    "id": "4",
    "value": "..",
    "localization": "EN"
}, {
    "id": "5",
    "value": "..",
    "localization": "EN"
}, {
    "id": "6",
    "value": "..",
    "localization": "EN"
}]

并且使用Alamofire,我发出了GET请求:

func getRequestWithAlamofire(){
    Alamofire.request("linkwhereIhosttheJSONFile").responseJSON { response in
        if let json = response.result.value {
        print("JSON: \(json)") // serialized json response
        }
    }
}

谢谢!

swift dictionary alamofire shuffle swifty-json
1个回答
0
投票

为JSON创建模型对象

struct Entry: Codable {
  let id, value, localization: String
}

并使用JSONDecoder对其进行解码:

do {
  let entries = try JSONDecoder().decode([Entry].self, from: data)
} catch {
  print(error)
}

一旦有了您就可以轻松选择具有localization == "NL"的随机元素:

let randomElement = entries.filter { $0.localization == "NL" }.randomElement()

(不需要Swift JSON)

© www.soinside.com 2019 - 2024. All rights reserved.