CONSUMING JSON WEB SERVICES

While most Web services currently in use were developed using XML and SOAP, they are inefficient for one primary reason: The use of XML makes data transfer expensive and slow (the start and end tags take up a huge portion of the document). Because the request and response packets use XML, it takes longer to transmit them, and parsing XML messages on the mobile device takes considerable effort.

Hence, if you are developing an end-to-end solution today, it is much better to use a non-XML based solution for the server side. A JSON Web service is one good candidate. JSON is a lightweight text-based open standard designed for human-readable data interchange. Using JSON, a Web service returns the result using a JSON string instead of an XML string. The following shows an example JSON string:

{
    “firstName”:“John”,
    “lastName”: “Smith”,
    “age”: 25,
    “address”:
    {

        “streetAddress”: “21 2nd Street”,
        “city”: “New York”,
        “state”: “NY”,
        “postalCode”: “10021”
    },
    “phoneNumber”:
    [
        {
            “type”: “home”,
            “212 555-1234”
        },
        {
            “type”: “fax”,
            “number”: “646 555-4567”
        }
    ]
}

Instead of using angle brackets to enclose data, JSON uses a series of braces, brackets, and colons to format the data. This formatting makes it very easy to parse the data into arrays and dictionary objects so that the relevant data can be extracted.

In the following Try It Out, you will learn how to consume a JSON Web service from your iPhone application.

TRY IT OUT: Consuming a JSON Web Service

  1. Using Xcode, ...

Get Beginning iOS 5 Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.