Understanding XML and JSON Parsing in iOS Programming

Updated on August 6th, 2014

⏱ Reading Time: 2 mins

One of the most important tasks that a developer has to deal with when creating applications is the data handing and manipulation. Data can be expressed in many different formats, and mastering at least the most known of them consists of a key ability for every single programmer. Speaking for mobile applications specifically now, it’s quite common nowadays for them to exchange data with web applications. In such cases, the way that data is expressed may vary, but usually is preferred either the JSON or the XML format.

iOS SDK provides classes for handling both of them. For managing JSON data, there is the NSJSONSerialization class. This one allows to easily convert a JSON data into a Foundation object (NSArray, NSDictionary), and the other way round. For parsing XML data, iOS offers the NSXMLParser class, which takes charge of doing all the hard work, and through some useful delegate methods gives us the tools we need for handling each step of the parsing.

Focusing a bit on each class separately, there’s not much to say about the NSJSONSerialization class, except for the fact that is very simple and straightforward to be used. There are some simple rules that should follow, but further than that it takes all the hassle away from us when some JSON conversion is needed. In order to convert a JSON value into a Foundation form, it has to be a NSData object. The returned converted object is either an array (NSArray), or a dictionary (NSDictionary). Their contained objects however can be instances of NSString, NSNumber, NSNull, and of course NSArray and NSDictionary. The NSJSONSerialization class provides ways for checking if a JSON data is valid before doing any conversion, so you can use it in order to make sure before performing any conversion. On the other hand now, when you need to turn a Foundation object into JSON, you should have in mind that the produced object is always of NSData type. As you assume from what I said until now, it looks like managing JSON as a string doesn’t seem to be an option, but that’s not true. As you’ll find out later in this tutorial, we can have the JSON expressed as a NSString object, simply by doing a small kind of trick.

Read the full tutorial on Appcoda

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on SerialCoder.dev.

    We respect your privacy. Unsubscribe at any time.