如何解析这个特定的JSON?

时间:2016-03-01 21:47:31

标签: json swift parsing

我试图解析这个JSON而我正试图获得"字段"括号并访问符号和价格。如果这是一个菜鸟问题,我很抱歉,老实说我不知道​​如何解析这个JSON,因为看起来好像你必须深入了解价格和符号。提前谢谢。

如果您需要,可以在此处找到JSON的链接:http://finance.yahoo.com/webservice/v1/symbols/aapl/quote?format=json

这里是json:

{
"list" : { 
    "meta" : { 
        "type" : "resource-list",
        "start" : 0,
        "count" : 1
    },
    "resources" : [ 
    {
        "resource" : { 
            "classname" : "Quote",
            "fields" : { 
                "name" : "Apple Inc.",
                "price" : "100.529999",
                "symbol" : "AAPL",
                "ts" : "1456866001",
                "type" : "equity",
                "utctime" : "2016-03-01T21:00:01+0000",
                "volume" : "50075193"
                }
            }
        }
    ]
  }
}

我到目前为止的代码:

 let requestURL: NSURL = NSURL(string: "https://finance.yahoo.com/webservice/v1/symbols/aapl/quote?format=json")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                if let test = json["fields"]!!["price"] as? [[String: AnyObject]] {

                } //end stations

            }catch {
                print("Error with Json: \(error)")

                //end catch
            }

        } //end if status code == 200
    } //end task


task.resume()

3 个答案:

答案 0 :(得分:1)

这样的事情,它假设json是根字典

if let resources = json["list"]?["resources"] as? [[String:AnyObject]] {
  if let fields = resources[0]["resource"]?["fields"] as? [String:String], price = fields["price"], symbol = fields["symbol"] {
    print(symbol, price)
  }
}

答案 1 :(得分:0)

对于“这个特定的JSON”:

objectName.list.resources[0].resource.fields.price

objectName.list.resources[0].resource.fields.symbol

如果您的对象包含多个这些数据集,则可以实现循环。

如果这个JSON对象是由你的脚本创建的,那么看看构建一个更有用的对象,这样你就不必太“深入”了。

答案 2 :(得分:0)

基本上你必须这样做,就像超人穿上裤子一样:一次一条腿。当然,符号和价格都埋藏在数据的深处,但那又如何呢?你只是继续潜水,比如从洋葱上剥下皮,直到你到达你想去的地方。

因此,如果d是您从网络获得的NSData:

let dict = try! NSJSONSerialization.JSONObjectWithData(d!, options:[])
let list = dict["list"] as! NSDictionary
let res = list["resources"] as! NSArray
let dict2 = res[0] as! NSDictionary
let res2 = dict2["resource"] as! NSDictionary
let fields = res2["fields"] as! NSDictionary
let symbol = fields["symbol"] as! String
let price = fields["price"] as! String