【问题标题】:Get an array instead of string获取数组而不是字符串
【发布时间】:2018-09-04 03:35:48
【问题描述】:

解析我的 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
        }
      }
    }
 }

【问题讨论】:

  • 后端未正确编码值。您需要让后端团队修复它,自己修复后端,或者手动解析该数组。
  • 是的,您需要修复 JSON。整数数组不应是 JSON 中的字符串。
  • 不相关,但在 Swift 中你不应该使用 NSDictionaryNSArrayNSDataNSURL 等。使用适当的 Swift 字典和数组。使用Data。使用URL。而且您可能不需要扩展NSObject

标签: arrays json swift string


【解决方案1】:

正如@Andy 所提到的,数组值没有以不正确的格式编码,因此被解码为字符串。格式应该如下

{
    "0": [31,47,51],
    "1": [74, 47, 51, 78],
    "2": [72, 65, 69, 80],
    "3": [63, 83, 87, 71]
}

如果你无法修复 json,下面的扩展应该可以解决问题

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)})

    }
}

并在你的arrayString上使用它,如下所示

myArray = myArrayString.toArray()

【讨论】:

  • 它也有效。 1000谢谢。现在我也按照rmaddy建议的方式解决了。
  • 不是手动处理字符串,数组字符串本身就是有效的 JSON。像解析普通 JSON 一样解析它。
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 2016-06-08
  • 2019-01-24
  • 2013-09-19
  • 2020-04-09
  • 1970-01-01
相关资源
最近更新 更多