Json Parsing in swift 3 using Alamofire

时光怂恿深爱的人放手 提交于 2020-01-24 19:56:05

问题


I am working in swift 3. I am new to ios. I am trying to parse the json data like

My jsonVlaue is : {
    data =     (
                {
            Password = "@1234";
            UserName = "<null>";
            "___class" = OrderTable;
            "__meta" = "{\"relationRemovalIds\":{},\"selectedProperties\":[\"UserName\",\"created\",\"name\",\"___class\",\"ownerId\",\"updated\",\"objectId\",\"Password\"],\"relatedObjects\":{}}";
            created = 1483525854000;
            name = TestMan;
            objectId = "4316DEBA-78C1-C7BD-FFBC-3CB77D747F00";
            ownerId = "<null>";
            updated = "<null>";
        },
                {
            Password = 123;
            UserName = "<null>";
            "___class" = OrderTable;
            "__meta" = "{\"relationRemovalIds\":{},\"selectedProperties\":[\"UserName\",\"created\",\"name\",\"___class\",\"ownerId\",\"updated\",\"objectId\",\"Password\"],\"relatedObjects\":{}}";
            created = 1483516868000;
            name = tommy;
            objectId = "29155114-C00B-5E1C-FF6F-7C828C635200";
            ownerId = "<null>";
            updated = "<null>";
        }.......

I want only the keyvalue:"name" and that value I want to add in an Array.

I tried to do like that but my app is getting Crash. My code i slike as follows

 func getLoginDetails()
    {
       //https://api.backendless.com/<version>/data/<table-name>/properties

        Alamofire.request( HeadersClass.api.domainName + "OrderTable", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HeadersClass.allHeaders.headers).responseJSON { response in
            //debugPrint(response)
            if let jsonDict = response.result.value as? NSDictionary {
                print("My jsonVlaue is : \(jsonDict)")

                 let arrayPracticeData: NSArray = jsonDict.value(forKey: "name") as! NSArray

                    print(arrayPracticeData)


            }

        }
}

Can anyone please tell me how to solve this. Thanks in Advance.


回答1:


First of all in Swift use Swift's native Array and Dictionary instead of NSDictionary and NSArray.

Now to get name you need to get Data array from your JSON response Dictionary. So try something like this.

Alamofire.request( HeadersClass.api.domainName + "OrderTable", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HeadersClass.allHeaders.headers).responseJSON { response in

     //debugPrint(response)
     if let jsonDict = response.result.value as? [String:Any], 
        let dataArray = jsonDict["data"] as? [[String:Any]] {
           let nameArray = dataArray.flatMap { $0["name"] as? String }
           print(nameArray)
     }
}

Output

["TestMan", "tommy", ...]


来源:https://stackoverflow.com/questions/41462844/json-parsing-in-swift-3-using-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!