首页 > 解决方案 > 有什么方法可以将键=值格式的字符串快速转换为字典?

问题描述

我有一个像这样的字符串:

{
    c = type3;
    com = posss;
    g = 40111;
    m = "xxxx";
}

我需要把它解析成字典。而且每次的响应键都不一样。期望是这样的:

let dictionary = ["c": "type3", "com": "posss", "g": "40111", "m": "xxxx"]

有任何想法吗?谢谢!

标签: swiftdictionary

解决方案


要回答您的问题,那就是 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])

# 但是 # ,

你是怎么得到这个值的?通常,这意味着有人给了你descriptionaNSDictionary而不是给你 a 的引用NSDictionary。一旦你澄清了谁是罪魁祸首,你就避免了这种转变,因为你做NSDictionaryNSString,而且你正在做回NSStringNSDictionary可能是矫枉过正,不是吗?)


推荐阅读