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

How to get a random value of a dictionary in swiftyJSON and Alamofire

我想得到 1(一) "value" 随机 顺序 "localization" "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
        }
    }
}

谢谢!

为您的 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 { [=12=].localization == "NL" }.randomElement()

(这些都不需要 SwiftyJSON)