Tometoyou
Tometoyou

Reputation: 8396

Converting String to [String : Any]

I have a string that defines an object like so:

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"
                        }
                        """

I need to convert it into the format [String : Any] but I'm not sure how to do this. In the past I have put the string into a json file and loaded that like this:

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

Anyone know how I can do this? Thanks!

Upvotes: 1

Views: 4127

Answers (2)

PGDev
PGDev

Reputation: 24341

In Swift 4, you can use JSONDecoder API to decode JSON data, i.e.

    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)
        {

        }
    }

Upvotes: 2

gnasher729
gnasher729

Reputation: 52632

Why are you doing it the complicated way in the first place? You want a dictionary, so define a dictionary.

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

Anyway, the NumberLong(0) isn't valid JSON, so that isn't going to work anyway.

Upvotes: 3

Related Questions