解析 JSON Swift 3

Posted

技术标签:

【中文标题】解析 JSON Swift 3【英文标题】:Parse JSON Swift 3 【发布时间】:2016-09-15 18:08:39 【问题描述】:

我整天都在寻找这个问题的答案,我快要崩溃和哭泣了,但是谁能告诉我或指出我将如何解析这个 JSON 文件的方向,以便我可以访问第一个“成员”数组并打印出所有人的名字?我现在看到的所有信息在 Swift 3 中都不起作用(!!!)。

JSON 文件:

    [
    
        "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"
            
        ]   
    
]

我不断收到错误消息“类型 'Any' 没有下标成员”,我只是不知道该怎么办了。我是这样解析数据的:

    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()

但是我不知道如何访问各个数组和字典。

谢谢!!

【问题讨论】:

您在parsedData 中有一个字典数组。忘记它当时来自JSON。您正在问一个关于迭代数组和从字典中获取键和值的非常基本的问题。两者的例子不胜枚举。你到底是什么问题? 我不知道它是如何工作的。谢谢! 我这里测试过,看来你只需要把NSMutableArray改成[[String: Any]] 【参考方案1】:

因为您的数组包含不同格式的项目。第一项包含 CEO 信息,其余项包含团队信息。

您可以通过检查当前项目是 CEO 或团队来解析它们

这是您在 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)

结果:

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

【讨论】:

【参考方案2】:
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()

【讨论】:

以上是关于解析 JSON Swift 3的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 3 中解析 JSON 数组

使用未解析的标识符 'json' (Swift 3) (Alamofire)

JSON解析错误Swift 3

解析 JSON Swift 3

如何使用 Alamofire 在 Swift 3 中解析 JSON?

在 Swift 3 中从 JSON 解析数组文字