简体   繁体   English

数组值的快速json字符串转换为[UInt8]

[英]swift json string with array value convert to [UInt8]

I have a json string: 我有一个json字符串:

let msg={\"type\":\"PONG\",\"content\":[52,55,49,56,51,54,56,56,55,46,57,52,54,55,57,50]}

and I use following code to parse: 我使用以下代码进行解析:

let receiveMsg = try NSJSONSerialization.JSONObjectWithData(NSString(string: msg!).dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary

then I could get the type by: 那么我可以通过以下方式获取类型:

let type = receiveMsg["type"]?.stringValue

I want to try the same way to get the array value by: 我想尝试以相同的方式通过以下方法获取数组值:

let content=receiveMsg["content"] as? [UInt8]

but unfortunately it fails. 但不幸的是它失败了。

The value of the key content is an array of Int . 关键content的值是一个Int数组。

You can convert it to [UInt8] with the map function 您可以使用map功能将其转换为[UInt8]

let content = receiveMsg["content"] as! [Int]
let contentUInt8 = content.map{UInt8($0)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM