0

I receive JSON objects that looks like the one below. How can I convert it into a format that is easily handled by Swift 2.1 ? I will receive several of these and have to put them into an array and sort by createdAt.

Optional({
    comment = "<null>";
    completedAt = "<null>";
    createdAt = "2015-11-02 15:01:04 +0000";
    paid = 1;
    paidAt = "2015-11-02 15:01:04 +0000";
    startedAt = "<null>";
    state = request;
    type = doctor;
    user = KTsCySacEAiz3eDnf;
    userdata =     {
        birthdate = "<null>";
        gender = "<null>";
    };
})
KML
  • 2,302
  • 5
  • 26
  • 47
  • Possible duplicate of [Swift: Extra argument 'error' in call](http://stackoverflow.com/questions/31073497/swift-extra-argument-error-in-call) – Eric Aya Nov 02 '15 at 16:15
  • Simple example for you in my linked answer. – Eric Aya Nov 02 '15 at 16:16
  • Hi, I looked at that, it gives me [_] is not convertible to NSJSONReadingOptions – KML Nov 02 '15 at 16:19
  • Hmm, I have version 2.1 Apple Swift version 2.1 (swiftlang-700.1.101.6 clang-700.1.76) – KML Nov 02 '15 at 16:23
  • 1
    How did you get the Optional you're showing in your question? Could you show this piece of code? We could try to adapt it for you. – Eric Aya Nov 02 '15 at 16:33
  • Thanks, but I gave up, just put all the individual fields into arrays instead - Thanks – KML Nov 02 '15 at 19:59

1 Answers1

-1

As in the title you say you expect a Dictionary, you can get one by simply serializate the json and cast it to a Dictionary.

do{
     let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
}catch{
     print("Something went wrong")
}

Where data is you json content as NSData. If you get a String you can easily convert it

let data = text.dataUsingEncoding(NSUTF8StringEncoding)
  • What do you mean by "Where data is you json content" mean? – KML Nov 02 '15 at 16:09
  • I now get 'Extra argument 'error' in call',... Are you sure this is swift 2.0 ? – KML Nov 02 '15 at 16:12
  • You change to 2.0 while writing the answer. Your code should look something like that. Swift 2.0 changed the way Error Handling must be done: https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch – Luis Miguel Sierra Nov 02 '15 at 16:35