【问题标题】:How to parse JSON using Alamofire in Swift 3.0 without any third-party library如何在没有任何第三方库的情况下在 Swift 3.0 中使用 Alamofire 解析 JSON
【发布时间】:2017-07-01 06:31:26
【问题描述】:

这里我想通过 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.
                }
            }
        }

请帮助我。我是新手。

【问题讨论】:

  • 尝试 arr["main"][0]["USDARS"],因为 "main" 是一个对象数组。
  • 您几天前没有发布同样的问题吗?我不记得您在之前的 cmets 或问题之后对代码进行了任何更改。我之前报道过:Why if let arr = response.result.value as? [String:AnyObject] then if let arr = response.result.value as? [NSDictionary] 这没有意义,你应该更喜欢 Swift Type 而不是 NSStuff。

标签: ios json swift swift3


【解决方案1】:
 @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()
}

【讨论】:

  • 不鼓励仅使用代码回答,因为它们没有为未来的读者提供太多信息,请对您所写的内容提供一些解释
【解决方案2】:

顶级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"])
           }
        }
    }

【讨论】:

  • 是的,它会打印“USDARS”的所有值,但我应该如何只打印“obj”的特定值或最后一个值
  • 首先 .. 你可以通过main.first?["USDARS"] .. 或者给出像main[0]["USDARS"]这样的索引
  • 好的,如果我想获得特定日期的价值,那么我应该怎么做?
  • 使用特定密钥 .. 代表日期 obj["date"] .. 代表 USDSDG obj["USDSDG"]
  • 很高兴它有帮助:)
【解决方案3】:

你应该使用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"

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 2014-10-13
    • 2012-03-23
    • 2018-04-11
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多