Parse JSON Swift 3

2019-06-14 14:50发布

I have been searching for an answer to this all day and I'm about to break down and cry but can anyone show me or point me in the direction of how I would parse this JSON file so that I could access the first array of 'members' and print out the first name of all of them? All of the info I looked at now doesn't work in Swift 3(!!!).

JSON file:

    [
    {
        "id" : "001",
        "firstName" : "Mark",
        "lastName" : "Mason",
        "role" : "CEO",
        "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
    },
    {
        "teamName" : "iOS",
        "members" : [
            {
                "id" : "002",
                "firstName" : "Olly",
                "lastName" : "Berry",
                "role" : "iOS Team Lead",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png",
                "teamLead" : true
            },
            {
                "id" : "003",
                "firstName" : "James",
                "lastName" : "Frost",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "004",
                "firstName" : "Liam",
                "lastName" : "Nichols",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "005",
                "firstName" : "Chris",
                "lastName" : "Watson",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "006",
                "firstName" : "Richard",
                "lastName" : "Turton",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "007",
                "firstName" : "Matt",
                "lastName" : "Colliss",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "008",
                "firstName" : "David",
                "lastName" : "Gibson",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "009",
                "firstName" : "Tom",
                "lastName" : "Guy",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "010",
                "firstName" : "Rich",
                "lastName" : "Hodgkins",
                "role" : "iOS Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            }
        ]
    },
    {
        "teamName" : "Android",
        "members" : [{
                "id" : "011",
                "firstName" : "David",
                "lastName" : "Branton",
                "role" : "Android Team Lead",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png",
                "teamLead" : true
            },
            {
                "id" : "012",
                "firstName" : "Dre",
                "lastName" : "Pilipczuk",
                "role" : "Android Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "013",
                "firstName" : "Ray",
                "lastName" : "Britton",
                "role" : "Android Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "014",
                "firstName" : "Charly",
                "lastName" : "Murillo",
                "role" : "Android Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            }
        ]   
    },
    {
        "teamName" : "Web",
        "members" : [{
                "id" : "015",
                "firstName" : "Ryan",
                "lastName" : "French",
                "role" : "Web Team Lead",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png",
                "teamLead" : true
            },
            {
                "id" : "016",
                "firstName" : "James",
                "lastName" : "Ward",
                "role" : "Web Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "018",
                "firstName" : "Adam",
                "lastName" : "Smith",
                "role" : "Web Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "019",
                "firstName" : "Leonard",
                "lastName" : "Da Costa",
                "role" : "Web Developer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            }
        ]   
    },
    {
        "teamName" : "Design",
        "members" : [{
                "id" : "020",
                "firstName" : "Hannah",
                "lastName" : "Tempest",
                "role" : "Design Team Lead",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png",
                "teamLead" : true
            },
            {
                "id" : "021",
                "firstName" : "Ellis",
                "lastName" : "Reed",
                "role" : "Designer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "022",
                "firstName" : "Pete",
                "lastName" : "Horsham",
                "role" : "Designer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "023",
                "firstName" : "Hemel",
                "lastName" : "Dave",
                "role" : "Designer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            },
            {
                "id" : "024",
                "firstName" : "Hannah",
                "lastName" : "Corke",
                "role" : "Designer",
                "profileImageURL" : "http://developers.mub.lu/resources/profilePlaceholder.png"
            }
        ]   
    }
]

I keep getting the error 'Type 'Any' has no subscript members' and I just don't know what to do anymore. I parsed the data like this:

    let urlString = "url of the json file"

            let url = URL(string: urlString)
            URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
                if error != nil {
                    print(error)
                } else {
                    do {

                        let parsedData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSMutableArray 
} catch let error as NSError {
                        print(error)
                    }
                }

            }).resume()

but then I have no idea how to access the individual arrays and dictionaries.

Thank you!!

2条回答
欢心
2楼-- · 2019-06-14 15:29

Because your array contain items not in same format. The first item contain CEO info, an rest items contain teams info.

You can parse them by check current items is CEO or teams

here's your parse code in Swift3

do {
    if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String: AnyObject]] {
        // parse data here
        for item in parsedData {
            if let ceoFirstName = item["firstName"] as? String { // first item is CEO info. You can get more info like id, lastName, role, profileImageURL here
                print("CEO firstName is \(ceoFirstName)")
            }
            if let teamName = item["teamName"], members = item["members"] as? [[String: AnyObject]] { // rest items are teams
                print("all members firstName from team \(teamName):")
                for member in members { // loop for all members
                    if let firstName = member["firstName"] as? String {
                        print("firstName = \(firstName)")
                    }
                    // you can get other member info like id, lastName, role, profileImageURL, teamLead here
                }

            }
        }

    }
} catch {
    print(exception)
}

result:

CEO firstName is Mark
all members firstName from team iOS:
firstName = Olly
firstName = James
firstName = Liam
firstName = Chris
firstName = Richard
firstName = Matt
firstName = David
firstName = Tom
firstName = Rich
all members firstName from team Android:
firstName = David
firstName = Dre
firstName = Ray
firstName = Charly
all members firstName from team Web:
firstName = Ryan
firstName = James
firstName = Adam
firstName = Leonard
all members firstName from team Design:
firstName = Hannah
firstName = Ellis
firstName = Pete
firstName = Hemel
firstName = Hannah
查看更多
欢心
3楼-- · 2019-06-14 15:46
let urlpath : String = "http://..."

let url = URL(string: urlpath)

var urlrequest = URLRequest(url: url!)

urlrequest.httpMethod = "GET"

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

let task = session.dataTask(with: urlrequest) { (data, response, error) in

    do {

        guard let getResponseDic = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
            else
        {
            print("error trying to convert data to JSON")
            return
        }
        // now we have the todo, let's just print it to prove we can access it

        print(getResponseDic as NSDictionary)

        let dic = getResponseDic as NSDictionary
        let msg = dic.object(forKey: "message")

        print(dic)
        let arrObj = dic.object(forKey: "teacherDetail") as! NSArray
        print(arrObj)

        // let arr = dic.value(forKey: "TeacherName")as! NSArray

        print(((dic.value(forKey: "teacherDetail") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "TeacherName") as! String)


        // the todo object is a dictionary
        // so we just access the title using the "title" key
        // so check for a title and print it if we have one

        // print("The title is: " + todoTitle)
    } catch  {
        print("error trying to convert data to JSON")
        return
    }

}

task.resume()
查看更多
登录 后发表回答