Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONSerialization with Swift 3

Tags:

json

swift

I am having a bear of a time understanding simple JSON serialization principles with Swift 3. Can I please get some help with decoding JSON from a website into an array so I can access it as jsonResult["team1"]["a"] etc? Here is relevant code:

let httprequest = URLSession.shared.dataTask(with: myurl){ (data, response, error) in

self.label.text = "RESULT"

    if error != nil {

        print(error)

    } else {

        if let urlContent = data {

            do {

                let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: 
                    JSONSerialization.ReadingOptions.mutableContainers)

                print(jsonResult) //this part works fine

                print(jsonResult["team1"])

                } catch {

                    print("JSON Processing Failed")
                }
            }
        }
    }
    httprequest.resume()

the incoming JSON is:

{
team1 = {
    a = 1;
    b = 2;
    c = red;
};

team2 = {
    a = 1;
    b = 2;
    c = yellow;
};
team3 = {
    a = 1;
    b = 2;
    c = green;
};
}

Thanks

like image 908
Frederic Avatar asked Sep 15 '16 21:09

Frederic


People also ask

What is Jsonserialization in Swift?

An object that converts between JSON and the equivalent Foundation objects.

What kind of Jsonserialization have Readingoptions?

Reading OptionsSpecifies that leaf strings in the JSON object graph are mutable. Specifies that the parser allows top-level objects that aren't arrays or dictionaries. Specifies that reading serialized JSON data supports the JSON5 syntax.

What is Swift Mutablecontainer?

Specifies that arrays and dictionaries in the returned object are mutable.


1 Answers

In Swift 3, the return type of JSONSerialization.jsonObject(with:options:) has become Any.

(You can check it in the Quick Help pane of your Xcode, with pointing on jsonResult.)

And you cannot call any methods or subscripts for the variable typed as Any. You need explicit type conversion to work with Any.

    if let jsonResult = jsonResult as? [String: Any] {
        print(jsonResult["team1"])
    }

And the default Element type of NSArray, the default Value type of NSDictionary have also become Any. (All these things are simply called as "id-as-Any", SE-0116.)

So, if you want go deeper into you JSON structure, you may need some other explicit type conversion.

        if let team1 = jsonResult["team1"] as? [String: Any] {
            print(team1["a"])
            print(team1["b"])
            print(team1["c"])
        }
like image 149
OOPer Avatar answered Nov 06 '22 05:11

OOPer