我有一个字符串来定义一个像这样的对象:
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"
}
"""
我需要将其转换为[String:Any]格式,但我不知道该怎么做。在过去,我已将字符串放入json文件并加载如下:
let data = NSData(contentsOfFile: file)
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: [])
let dict = json as! [String: Any]
任何人都知道如何做到这一点?谢谢!
答案 0 :(得分:2)
你为什么一开始就以复杂的方式做这件事?你想要一本字典,所以要定义一本字典。
item1
无论如何,NumberLong(0)不是有效的JSON,因此无论如何都不会起作用。
答案 1 :(得分:1)
在 Swift 4 中,您可以使用 JSON
API来解码 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)
{
}
}
数据,即
{{1}}