如何在没有任何第三方库的Swift 3.0中使用Alamofire解析JSON

时间:2017-02-13 09:59:17

标签: ios json swift swift3

这里我想通过url解析JSON。这是url上可用的实际JSON数据。所以我需要解析它并使用Alamofire在我的应用程序中阅读。但我无法做到。

我的网址中的JSON数据。

  {
        "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"
        }
    ]
}

如何在swift 3.0中使用Alamofire阅读它

以下是我尝试通过url解析JSON数据以上的内容。

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.
                }
            }
        }

请帮帮我。我是新手。

3 个答案:

答案 0 :(得分:6)

顶级json为[String:Any],main为数组,即[[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"])
           }
        }
    }

答案 1 :(得分:0)

你应该使用SwiftyJson,这是一个用于json解析的库,对Alamofire非常有用

在你的情况下,你可以用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"

答案 2 :(得分:0)

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