parse json rfc 4267

I want to parse or deserialization a nested or hierarchical json by swift that

is valid according to RFC 4627 (JSON specfication).


(
    {
        key1 =
            (
                {
                    key11 = "value11";
                    key12 = "value12";
                }
            );
        key2 =
            (
                {
                    key21 = 1;
                }
            );
    }
)


Can i parse it whiteout library such as ObjectMapper , JSONJoy and Argo?


my xcode version is 6.1 (6A1052c) and my os x version is 10.10 (Yosemite)

Can i parse it whiteout library such as ObjectMapper , JSONJoy and Argo?

Depends on what you mean by `it`.


With NSJSONSerialization class you can parse RFC 4627 compliant JSON data.

NSJSONSerialization Class Reference


But the lines you have shown above does not conform to JSON specification, it looks like a text representation of plist. If you need to parse such files, you need another way.


Which do you want to parse, JSON or plist?

Sorry for my bad English.

English isn’t my first language, so please excuse any mistakes.


thanks, i know can parse with NSJSONSerialization but i dont know how

should i call

JSONObjectWithData
twice or ...?

i need swift code example for above code. or sample for parse nested json.

or

i have sample for parse non nested json. how i change this sample for nested json.


swift code

let myUrl = NSURL(string: "http://www.testdomain.com/test.php/");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = “POST”;

// Compose a query string
let postString = “firstName=James&lastName=Bond”;

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil
{
println(“error=\(error)”)
return
}

// You can print out response object
println(“response = \(response)”)



// Print out response body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(“responseString = \(responseString)”)




//Let’s convert response sent from a server side script to a NSDictionary object:

var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

if let parseJSON =myJSON {
// Now we can access value of First Name by its key
var firstNameValue = parseJSON[“firstName”] as? String
println(“firstNameValue: \(firstNameValue)”)
}




}

task.resume()


test.php

<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array
$returnValue = array(“firstName”=>$firstName, “lastName”=>$lastName);

// Send back request in JSON format
echo json_encode($returnValue); ?>

there isn't any sample for parse nested json?

Once you call JSONObjectWithData, you get a nested data structure for you nested JSON. And how to use the data structure depends on the actual structure.

Show you actual JSON data, with your code (which need not be `perfect`, just that you better show what you have done till now seeing the class referece) .


I couldn't find a good example in Apple's sample code Library.

I’m not entirely sure what you mean by “nested json” but I suspect that you’re asking how to parse a dictionary within a dictionary. If so, here’s an example.

Let’s start with JSON data like this:

7b0a2020 22616464 72657373 22203a20
7b0a2020 2020227a 6970436f 64652220
3a202239 35303134 222c0a20 20202022
73747265 65744164 64726573 7322203a
20223120 496e6669 6e697465 204c6f6f
70222c0a 20202020 22636f75 6e747279
22203a20 22555341 220a2020 7d2c0a20
20226e61 6d652220 3a202241 70706c65
20496e63 2e220a7d

As text this looks like this:

{
  "address" : {
    "zipCode" : "95014",
    "streetAddress" : "1 Infinite Loop",
    "country" : "USA"
  },
  "name" : "Apple Inc."
}

You parse out the name and country like this:

do {
    let rootUntyped = try NSJSONSerialization.JSONObjectWithData(data, options: [])
    guard let rootDict = rootUntyped as? NSDictionary else {
        throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
    }

    guard let name = rootDict["name"] as? String else {
        throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
    }

    guard let address = rootDict["address"] as? NSDictionary else {
        throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
    }

    guard let country = address["country"] as? String else {
        throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadCorruptFileError, userInfo: nil)
    }

    NSLog("name: %@", name)
    NSLog("country: %@", country)
} catch let error as NSError {
    NSLog("%@", error)
}

When run this prints:

2015-11-13 12:00:06.438 JSONTest[33964:2590782] name: Apple Inc.
2015-11-13 12:00:06.438 JSONTest[33964:2590782] country: USA

Now, this is a lot of code and there are better ways to do this (parsing JSON is like the “Hello World!” of Swift, that is, it’s a common place to start learning the details of the language) but the above works and represents a direct translation of how you might do it in Objective-C.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
parse json rfc 4267
 
 
Q