Swift - 如何从AnyObject中提取字节数组

时间:2017-10-03 04:19:46

标签: swift

我有json数据。这是一个片段:

{"entries":[{"a":"153","b":"7","d":[0,0,4,-122,-1,0,0,-1,-64,64,-26,34,35,120]}

我已经提取了"条目"创建[[String:AnyObjects]]并将其传递给函数" entryFromJSONObject"

fileprivate func entryFromJSONObject(json: [String : AnyObject]) {
    let _id = json["a"] as? String,
    let cidA = json["b"] as? String,
    let dataArray = json["d"] as? Array<UInt8>
    // etc
}

此代码成功解析&#34; id&#34;和&#34; cidA&#34;但总是无法创建名为dataArray的数据数组。

我已经广泛搜索了如何将AnyObject转换/转换为UInt8数组,但无法找到有效的答案。通过xcode 9.0我已经验证了json [&#34; d&#34;]的类型是Swift.AnyObject?并且数据在内存中。

我如何实现我的目标?我使用的是Swift 3.2。这段代码可能在Swift的早期版本中有效 - 或者我在测试时遇到了错误!

1 个答案:

答案 0 :(得分:1)

您可以将字节值转换为Int8并使用UInt8(bitPattern :)初始值设定项将其映射为字节:

let jsonStr = """
{"entries":[{"a":"153","b":"7","d":[0,0,4,-122,-1,0,0,-1,-64,64,-26,34,35,120]}]}
"""
let jsonDict = try! JSONSerialization.jsonObject(with: Data(jsonStr.utf8)) as! [String : Any]

func entryFromJSONObject(json: [String : Any]) {
    if let dictionaries = json["entries"] as? [[String: Any]],
        let dict = dictionaries.first,
        let id = dict["a"] as? String,
        let cidA = dict["b"] as? String,
        let dataArray = dict["d"] as? Array<Int8>  {
        print(id)    // "153\n"
        print(cidA)  // "7\n"
        print(dataArray) // "[0, 0, 4, -122, -1, 0, 0, -1, -64, 64, -26, 34, 35, 120]\n"
        let bytes = dataArray.flatMap { UInt8(bitPattern: $0) }
        print(bytes)  // [0, 0, 4, 134, 255, 0, 0, 255, 192, 64, 230, 34, 35, 120]\n"
    }
}

如果您只是从条目词典数组中传递第一个词典,则可以执行以下操作:

let jsonDic = """
{"a":"153","b":"7","d":[0,0,4,-122,-1,0,0,-1,-64,64,-26,34,35,120]}
"""
let jsonDict = try! JSONSerialization.jsonObject(with: Data(jsonDic.utf8)) as! [String : Any]
func entryFromJSONObject(json: [String : Any]) {
        if let id = json["a"] as? String,
        let cidA = json["b"] as? String,
        let dataArray = json["d"] as? Array<Int8>  {
        print(id)    // "153\n"
        print(cidA)  // "7\n"
        print(dataArray) // "[0, 0, 4, -122, -1, 0, 0, -1, -64, 64, -26, 34, 35, 120]\n"
        let bytes = dataArray.flatMap { UInt8(bitPattern: $0) }
        print(bytes)  // [0, 0, 4, 134, 255, 0, 0, 255, 192, 64, 230, 34, 35, 120]\n"
    }
}

entryFromJSONObject(json: jsonDict)