从Json中随机读取字符串

从Json中随机读取字符串,json,swift3,Json,Swift3,我有一个Json文件,如下所示: { 9898989, 7878787, 1212121, 2323232, 4545454, 3434343 } let inputData = try! Data(contentsOf: Bundle(for: type(of: self)).url(forResource: "tests_config", withExtension: "json")!) let configDictionary = try

我有一个Json文件,如下所示:

{
    9898989,
    7878787,
    1212121,
    2323232,
    4545454,
    3434343
}
let inputData = try! Data(contentsOf: Bundle(for: type(of: self)).url(forResource: "tests_config", withExtension: "json")!)

let configDictionary = try! JSONSerialization.jsonObject(with: inputData, options: JSONSerialization.ReadingOptions()) as! NSDictionary
现在,我希望Swift3代码从json文件中随机读取一个id(
tests\u config.json

我的代码现在显示如下:

{
    9898989,
    7878787,
    1212121,
    2323232,
    4545454,
    3434343
}
let inputData = try! Data(contentsOf: Bundle(for: type(of: self)).url(forResource: "tests_config", withExtension: "json")!)

let configDictionary = try! JSONSerialization.jsonObject(with: inputData, options: JSONSerialization.ReadingOptions()) as! NSDictionary
当我想调用我使用的函数时:

showDetailsPage(forProductID: configDictionary[ONE OF THE IDs IN THE JSON] as! Int)
我假设您有一个字符串,其内容如下:

[
    9898989,
    7878787,
    1212121,
    2323232,
    4545454,
    3434343
]
(否则,它不是字符串)

然后,由于无法直接访问字符串的特定元素,因此需要在数组中转换json字符串:

let data = string.data(using: .utf8)!
let array = try! JSONSerialization.jsonObject(with: data, options: []) as! [Int]
然后,随机选取一个元素:

let ONE_OF_THE_IDs = array[Int(arc4random_uniform(UInt32(array.count)))]
let myArray = ["2323232", "4545454", "3434343", "7878787"]
let ONE_OF_THE_IDs = Int(myArray[Int(arc4random_uniform(UInt32(myArray.count)))])!
(当然,只有在数据是硬编码的情况下才强制尝试和强制展开,就像您的示例中所示)


[编辑] 如果您已经有了一个数组,那么与JSON无关。直接随机选取一个元素:

let ONE_OF_THE_IDs = array[Int(arc4random_uniform(UInt32(array.count)))]
let myArray = ["2323232", "4545454", "3434343", "7878787"]
let ONE_OF_THE_IDs = Int(myArray[Int(arc4random_uniform(UInt32(myArray.count)))])!

首先,这不是有效的JSON。接下来,您需要的是数组,而不是字典。然后搜索
[swift]随机数组元素
,您会找到很多解决方案。首先感谢您的帮助。现在我已经编写了这样一个数组:1让myArray=[“2323232”,“4545454”,“3434343”,“7878787”]2让data=string.myArray.data(使用:.utf8)!3让数组=尝试!JSONSerialization.jsonObject(带有:data,选项:[])as![Int]4让其中一个\u id=array[Int(arc4random\u uniform(UInt32(array.count))),但现在第2行有一个bug“使用未解析的标识符“字符串”。是否可以将第一行放入一个额外的文件(如“file.data”)中,以及如何读取它。如果您已经有了
myArray
,则不需要任何json转换。直接选择一个随机值。谢谢,当我已经有一个数组时的版本现在可以正常工作了。只有当我想把它放在一个额外的Json文件中时,它才会起作用。