在提到的网址中,我只需要从网址中获取第一本字典吗?
Posted
技术标签:
【中文标题】在提到的网址中,我只需要从网址中获取第一本字典吗?【英文标题】:In the mentioned url i need to get only first dictionary from the url? 【发布时间】:2017-07-20 08:40:27 【问题描述】:在这个订单详细信息数组中,我有 10 个字典,但我只需要显示第一个字典,谁能帮我实现这个?
http://www.json-generator.com/api/json/get/bUKEESvnvS?indent=2
下面是我的代码
func downloadJsonWithURL()
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: (data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
self.orderdetailsArray = (jsonObj!.value(forKey: "Orders detail") as? [[String: AnyObject]])!
for array in self.orderdetailsArray
let key = "OrderId"
let value = "#1000501"
for (key,value) in array
if let addressDict = array as? NSDictionary
if let orderid = addressDict.value(forKey: "OrderId")
self.orderid.append(orderid as! String)
if let orderdate = addressDict.value(forKey: "OrderDate")
self.orderdate.append(orderdate as! String)
if let subtotal = addressDict.value(forKey: "SubTotal")
self.subTotal.append(subtotal as! Int)
if let Shipping = addressDict.value(forKey: "Shipping")
self.shippingPrice.append(Shipping as! Int)
if let tax = addressDict.value(forKey: "Tax")
self.tax.append(tax as! Int)
if let grandtotal = addressDict.value(forKey: "GrandTotal")
self.grandTotal.append(grandtotal as! Int)
if let shippingAddress = addressDict.value(forKey: "ShippingAddress")
self.shippingAddress.append(shippingAddress as AnyObject)
if let shippingMethod = addressDict.value(forKey: "ShippingMethod")
self.shippingMethod.append(shippingMethod as AnyObject)
if let billingAddress = addressDict.value(forKey: "BillingAddress")
self.billingAddress.append(billingAddress as AnyObject)
if let paymentMethod = addressDict.value(forKey: "PayMentMethod")
self.paymentMethod.append(paymentMethod as AnyObject)
self.itemsArray = addressDict.value(forKey: "Items detail") as! [[String : AnyObject]]
OperationQueue.main.addOperation(
self.tableDetails.reloadData()
)
).resume()
【问题讨论】:
基本上你只需要从响应中获取第一个条目吗? 是的第一本词典@Joshua @VamsiKrishna 如果我的回答解决了您的问题,请务必将我的回答标记为有用 是的兄弟@SamarthKejriwal 如何显示商品详情:["ItemQty": 3] 你这样做了吗 【参考方案1】:这样做。 :
let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
guard let Ordersdetail = jsonObj["Orders detail"] as? [NSDictionary] else
print("Cannot find key 'Orderdetails' in \(jsonObj)")
return
要访问第一个字典的内容,请执行以下操作:
var orderid = Ordersdetail[0]["OrderId"]!
var shippingadress = Ordersdetail[0]["ShippingAddress"]!
var total = Ordersdetail[0]["GrandTotal"]!
var subtotal = Ordersdetail[0]["SubTotal"]!
var tax = Ordersdetail[0]["Tax"]!
var shipping = Ordersdetail[0]["Shipping"]!
【讨论】:
您不应在 Swift 中使用NSDictionary
,而应使用原生 Swift 替代方案 Dictionary
。
是的,这是可以接受的。我忘了纠正它:) 谢谢【参考方案2】:
你好,如果你想要第一个字典
self.orderdetailsArray
然后
if let firstDictInfo = self.orderdetailsArray.first as? [String:Any]
// Do your stuff here
print(firstDictInfo["OrderId"])
【讨论】:
在第一个字典中我需要如何获取剩余的键值对,即 orderid、orderdate 等【参考方案3】:而不是遍历整个字典是字典,你应该只取第一个字典并只解析它。您的代码还有很多其他概念性问题。在 Swift 中,不要使用NSDictionary
,而是使用原生 Swift 版本,Dictionary
,它保留了其内容的类型信息。此外,使用条件转换确保即使接收到的数据错误/意外,您的程序也不会崩溃,并且不要使用强制解包选项。
此外,在 Swift 中解析 JSON 响应时,通常没有必要也不是一个好主意来遍历响应中字典的键值对。您应该知道您期望的数据结构,否则您将无法正确解析它,并且由于您可以在 Swift 中直接访问字典值,如果您知道它对应的键,则无需在循环中遍历字典。
func downloadJsonWithURL()
let url = URL(string: self.url)
URLSession.shared.dataTask(with: url!, completionHandler: (data, response, error) -> Void in
if let jsonObj = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? [String:Any]
guard let self.orderdetailsArray = jsonObj["Orders detail"] as? [[String: AnyObject]] else return
guard let firstOrderDetails = self.orderdetailsArray.first else return
let key = "OrderId"
let value = "#1000501"
if let ordered = firstOrderDetails["OrderId] as? String
self.orderid.append(orderid)
if let orderdate = firstOrderDetails["OrderDate"] as? String
self.orderdate.append(orderdate)
if let subtotal = firstOrderDetails["SubTotal"] as? Int
self.subTotal.append(subtotal)
if let shipping = firstOrderDetails["Shipping"] as? Int
self.shippingPrice.append(shipping)
if let tax = firstOrderDetails["Tax"] as? Int
self.tax.append(tax)
if let grandtotal = firstOrderDetails["GrandTotal"] as? Int
self.grandTotal.append(grandtotal)
if let shippingAddress = firstOrderDetails[ "ShippingAddress"] as? AnyObject //why don't you store it as a String?
self.shippingAddress.append(shippingAddress)
if let shippingMethod = firstOrderDetails[ "ShippingMethod"] as? AnyObject
self.shippingMethod.append(shippingMethod)
if let billingAddress = firstOrderDetails[ "BillingAddress"] as? AnyObject
self.billingAddress.append(billingAddress)
if let paymentMethod = firstOrderDetails ["PayMentMethod"] as? AnyObject
self.paymentMethod.append(paymentMethod)
guard let itemDetails = firstOrderDetails["Items detail"] as? [[String : AnyObject]] else return
self.itemsArray = itemDetails
OperationQueue.main.addOperation(
self.tableDetails.reloadData()
)
).resume()
我尚未编译和运行代码,因此请务必检查是否有任何拼写错误/不一致之处。此外,请确保将存储的对象的类型从 AnyObjects 更改为特定类型。
【讨论】:
以上是关于在提到的网址中,我只需要从网址中获取第一本字典吗?的主要内容,如果未能解决你的问题,请参考以下文章
从页面操作中获取标签网址(WebExtensions,Android)