解析JSON之后,我得到以下值:
myArray = "[63, 83, 87, 71]"
如何获取数组而不是字符串?我需要的是:
myArray = [63, 83, 87, 71]
更新:
这是我简单的json:
{
"0": "[31,47,51]",
"1": "[74, 47, 51, 78]",
"2": "[72, 65, 69, 80]",
"3": "[63, 83, 87, 71]"
}
这里是解析:
class gameModel: NSObject {
func getCurrentArrays() -> NSDictionary {
let appBundlePath:String? = Bundle.main.path(forResource: "testJsonPrepared", ofType: "json")
if let actualBundlePath = appBundlePath {
let urlPath:NSURL? = NSURL(fileURLWithPath: actualBundlePath)
if let actualUrlPath = urlPath {
let jsonData:NSData? = NSData(contentsOf: actualUrlPath as URL)
if let actualJsonData = jsonData {
let dict: NSDictionary? = (try? JSONSerialization.jsonObject(with: actualJsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary?
if let currentArrays = dict {
return currentArrays
}
}
}
}
return NSDictionary()
}
}
这是决赛:
class GameScene: SKScene {
let model = gameModel()
var arrays: NSDictionary = ["":""]
override func didMove(to view: SKView) {
arrays = model.getCurrentArrays()
print("# func viewDidLoad arrays: \(arrays)")
let testKey = String(3)
let testArray = arrays.value(forKey: testKey) as! String
print("# func viewDidLoad testArray: \(testArray)")
}
}
===========
Update2谢谢,rmaddy。这是我的解决方案:
testJson.json
{
"0": [31,47,51],
"1": [74, 47, 51, 78],
"2": [72, 65, 69, 80],
"3": [63, 83, 87, 71]
}
这是从json中读取的内容:
class GameScene: SKScene {
override func didMove(to view: SKView) {
if let path = Bundle.main.path(forResource: "testJson", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, [Int]>, let array = jsonResult["3"] {
print("# func didMove array: \(array)")
}
} catch {
// handle error
}
}
}
}
答案 0 :(得分:0)
正如@Andy所提到的,数组值未以不正确的格式进行编码,因此被解码为字符串。格式应如下
SQL> select * from employee;
12 sachin 48000 23
13 raja 49000 23
35 vikas 40000 26
11 sau 22000 24
23 viru 40000 26
87 raju 4500
如果您无法修复json,则应使用以下扩展名
{
"0": [31,47,51],
"1": [74, 47, 51, 78],
"2": [72, 65, 69, 80],
"3": [63, 83, 87, 71]
}
并按如下所示在ur arrayString上使用它
extension String{
func toArray()->[Int]{
var trimmedStr = self.replacingOccurrences(of: "[", with: "")
trimmedStr = self.replacingOccurrences(of: "]", with: "")
let strArray = trimmedStr.components(separatedBy: ",")
return strArray.flatMap({Int($0)})
}
}