Creating a JSON object in Swift

I am trying to send JSON data to a server from my iOS application. I found a tutorial at this link.
What obj: AnyObject should look like so that this method can be called:

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

It does not accept a dictionary (although it is somehow used in the example from the link above) or Array.

0
source share
1 answer

Suppose you have a dictionary like

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

To generate JSON data using the method you specified, just name it:

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

You can check if this works by analyzing the generated data:

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

Source: https://habr.com/ru/post/984822/


All Articles