1

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!

1
  • Don't create an NSData instance when you need a Data object. Call the appropriate initializer of Data. Commented Oct 6, 2017 at 13:58

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.