将字符串转换为 [字符串:任意]



我有一个字符串来定义一个对象,如下所示:

let object = """
                        {
                              "id": 59d75ec3eee6c20013157aca",
                              "upVotes": NumberLong(0),
                              "downVotes": NumberLong(0),
                              "totalVotes": NumberLong(0),
                              "timestamp" : "(minutesAgo(1))",
                              "caption": "hello",
                              "username": "hi",
                              "commentsCount": NumberLong(0),
                              "lastVotingMilestone": NumberLong(0),
                              "type": "Text"
                        }
                        """

我需要将其转换为格式 [字符串:任意],但我不确定如何做到这一点。过去,我将字符串放入 json 文件中并像这样加载:

let data = NSData(contentsOfFile: file)      
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: [])
let dict = json as! [String: Any]

有人知道我该怎么做吗?谢谢!

你为什么要以复杂的方式做这件事?你想要一个字典,所以定义一个字典。

let dict: [String: Any] = [
    "id": "59d75ec3eee6c20013157aca",
    "upVotes": 0,
    "downVotes": 0, 
    ...
]

无论如何,NumberLong(0) 不是有效的 JSON,所以无论如何这都行不通。

Swift 4 中,您可以使用JSONDecoder API 来解码JSON数据,即

    let object = """
    {
    "id": 59d75ec3eee6c20013157aca",
    "upVotes": NumberLong(0),
    "downVotes": NumberLong(0),
    "totalVotes": NumberLong(0),
    "timestamp" : "Some Value",
    "caption": "hello",
    "username": "hi",
    "commentsCount": NumberLong(0),
    "lastVotingMilestone": NumberLong(0),
    "type": "Text"
    }
    """
    if let data = object.data(using: .utf8)
    {
        if let dict = try? JSONDecoder().decode([String: Any].self, from: data)
        {
        }
    }

最新更新