Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

json - JSONSerialization with Swift 3

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"])
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...