我有一个像这样的Json文件:
{
9898989,
7878787,
1212121,
2323232,
4545454,
3434343
}
现在,我希望Swift3代码从json文件(tests_config.json
)中随机读取其中一个id。
我的代码目前显示如下:
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)
答案 0 :(得分:0)
我假设你有字符串,内容如下:
[
9898989,
7878787,
1212121,
2323232,
4545454,
3434343
]
(否则,它不是json字符串)
然后,由于没有直接访问String的特定元素,您需要在数组中转换json string :
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)))]
(当然,如果您的数据是硬编码的,只有强制尝试并强制解包,就像您的示例中所示)
[编辑] 如果您已经有数组,则没有任何与JSON相关的内容。直接随机选择一个元素:
let myArray = ["2323232", "4545454", "3434343", "7878787"]
let ONE_OF_THE_IDs = Int(myArray[Int(arc4random_uniform(UInt32(myArray.count)))])!