Json Parsing in swift 3 using Alamofire

2019-07-29 10:35发布

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条回答
疯言疯语
2楼-- · 2019-07-29 11:12

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", ...]
查看更多
登录 后发表回答