swift - 有什么方法可以将键=值格式的字符串快速转换为字典?
问题描述
我有一个像这样的字符串:
{
c = type3;
com = posss;
g = 40111;
m = "xxxx";
}
我需要把它解析成字典。而且每次的响应键都不一样。期望是这样的:
let dictionary = ["c": "type3", "com": "posss", "g": "40111", "m": "xxxx"]
有任何想法吗?谢谢!
解决方案
要回答您的问题,那就是 OpenStep 格式。
如果你这样做:
let dictionary = ["c": "type3", "com": "posss", "g": "40111", "m": "xxxx"]
print("dictionary: \(dictionary as! NSDictionary)")
这就是你得到的格式。基本上,这就是打印NSArray
/的方式NSDictionary
,即“Objective-C”属性列表(对方法的内部调用description
)
现在,有一种方法可以将其取回(毕竟.pbxcodeproj是这种格式,Xcode 必须将其读回)PropertyListSerialization
:
let rawDataStr = """
{
c = type3;
com = posss;
g = 40111;
m = "xxxx";
}
"""
let rawData = Data(rawDataStr.utf8)
var format: PropertyListSerialization.PropertyListFormat = .openStep
do {
let serialized = try PropertyListSerialization.propertyList(from: rawData, options: [], format: &format)
print(serialized) //By default, it's a NSDictionary, so you'll get the same output, note that the order of the item may change
print(serialized as? [String: Any])
} catch {
print("Error: \(error)")
}
输出:
$>{
c = type3;
com = posss;
g = 40111;
m = xxxx;
}
$>Optional(["com": posss, "c": type3, "m": xxxx, "g": 40111])
# 但是 # ,
你是怎么得到这个值的?通常,这意味着有人给了你description
aNSDictionary
而不是给你 a 的引用NSDictionary
。一旦你澄清了谁是罪魁祸首,你就避免了这种转变,因为你做NSDictionary
了NSString
,而且你正在做回NSString
(NSDictionary
可能是矫枉过正,不是吗?)
推荐阅读
- boolean - 我不能证明 ((m xor a) xor (m and a))= (m or a)
- php - PHP Laravel 下拉列表
- c# - 使用 aspx 页面时可以停止任务吗?
- python - 关于动画的Python pygame noob问题
- bash - 如何输入令牌而不在终端中留下历史记录?
- discord.py - 如何将 DM 发送给命令作者?
- javascript - ThreeJS 加载 GLTF 并使用 FabricJS 画布作为纹理
- vue.js - "Mustache" syntax alternative for Vue template when using Pug language
- python - Scrapy startproject 不起作用权限被拒绝:蜘蛛
- amazon-web-services - 为什么我无法从我的 PC 连接到新的 AWS Aurora Serverless 实例?