1

I'm trying to send JSON data to a server from my iOS app. I found a tutorial on this link.
How should the "obj: AnyObject" look like so that this method can be called:

NSJSONSerialization.dataWithJSONObject(obj: AnyObject, options: NSJSONWritingOptions, error: NSErrorPointer)

It doesn't accept Dictionary (even though it is somehow used in the example on the link above) or Array.

1 Answer 1

4

Let's assume you have a dictionary like

let dictionary = ["key1": "value1", "key2": "value2"]

To generate your JSON Data using the method you provided you just call it:

var jsonGenerationError: NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted, error: &jsonGenerationError)

You can verify it worked by parsing the generated data:

var jsonParsingError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments, error:&jsonParsingError)

Swift 4

let dictionary = ["key1": "value1", "key2": "value2"]
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
// Verifying it worked:
let parsedObject = try! JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. The problem was that I didn't finish writing the method and the error appeared, even though it was a valid object (in this case dictionary) that I was passing as the first argument.

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.