2017-10-06 145 views
0

我有一個定義,像這樣一個對象的字符串:轉換字符串[字符串:任何]

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] 

任何人都知道我能做到這一點?謝謝!

+0

當你需要一個'Data'對象不創建'NSData'實例。調用'Data'的適當初始化程序。 –

回答

2

爲什麼你要做這個複雜的方式呢?你想要一本字典,所以定義一本字典。

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

無論如何,NumberLong(0)是無效的JSON,因此無論如何都不會起作用。

1

斯威夫特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) 
     { 

     } 
    }