简体   繁体   中英

How to parse JSON using Alamofire in Swift 3.0 without any third-party library

Here I want to parse JSON via url. This is what actual JSON data available on url. So I need to parse it and read in my app using Alamofire. But I 'm unable to do it.

JSON Data in my url.

  {
        "main": [
        {
        "date": "2017-01-11",
        "USDARS": "15.8302",
        "USDCLP": "670.400024",
        "USDSDG": "6.407695"
        },
        {
        "date": "2017-01-12",
        "USDARS": "15.804999",
        "USDCLP": "661.599976",
        "USDSDG": "6.407697"
        },
        {
        "date": "2017-01-13",
        "USDARS": "15.839041",
        "USDCLP": "659.200012",
        "USDSDG": "6.407704"
        },
        {
        "date": "2017-01-14",
        "USDARS": "15.839041",
        "USDCLP": "659.200012",
        "USDSDG": "6.407704"
        }
    ]
}

How do I read it using Alamofire in swift 3.0

Below is what actually I'm trying to parse above JSON data via url.

Alamofire.request("myurl") .responseJSON { response in

            print("In Alamofire")
            if let arr = response.result.value as? [String:AnyObject]
            {

                if let arr = response.result.value as? [NSDictionary]
                {
                    let val1 = (arr["main"]["USDARS"] as? String)
                    print(val1)
                    //It does not print any thing.
                }
            }
        }

Please help me. I'm new to it.

Top level json is [String:Any] and main is an array ie [[String:String]]

    Alamofire.request("myurl") .responseJSON { response in
        if let result = response.result.value as? [String:Any], 
           let main = result["main"] as? [[String:String]]{
           // main[0]["USDARS"] or use main.first?["USDARS"] for first index or loop through array
           for obj in main{
               print(obj["USDARS"])
               print(obj["date"])
           }
        }
    }

You should use SwiftyJson , which is a library for json parsing, very usefull with Alamofire

In your case you can do something like this with swiftyJson :

//Array & Dictionary
var jsonArray: JSON =  [
   "main": ["date": "2017-01-11", "USDARS": "15.8302"]
]

let dateString = jsonArray["main"][0]["date"].string

print(dateString) = "2017-01-11"
 @IBAction func btnget(_ sender: UIButton) {

    let urlpath : String = "http://202.131.123.211/UdgamApi_v4/App_Services/UdgamService.asmx/GetAllTeacherData?StudentId=2011111"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM