从 NSDictionary 获取 JSON 数据
Get JSON data from NSDictionary
我的 api
中有结构
{
"Hall":"Hall",
"Date":20180501,
"Prices":[
{
"Time":1,
"Price":4000
},
{
"Time":2,
"Price":4000
},
{
"Time":3,
"Price":4000
}
]
}
现在卡住了,拉不出价格和时间。我明白了很多问题,但我还是不明白,请帮助。
我使用这个代码:
let url = URL(string: "http://<...>/api/prices?hall=<...>&date=20180501")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let err = error {
print(err)
} else {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
// ...
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
} catch {
print("error")
}
}
})
task.resume()
}
我是 json 的新手,刚开始学习它。我知道这很容易,但我想不通。我也知道我可以使用 codable 和 decodable,但现在我需要在这个实现中获得价格和时间。
产品结构:
struct Product{
let time:Int
let price:Int
init(_ object:[String:Int]){
self.time = object["Time"] ?? 0
self.price = object["Price"] ?? 0
}
}
Class变量:
var products = [Product]()
JSON 解析:
do{
if let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] {
//Use Swift dictionary instead of NSDictionary
if let prices = jsonObject["Prices"] as? [[String:Int]]{
for price in prices{
self.products.append(Product(price))
}
}
}
}catch{
print("Error: ",error.localizedDescription)
}
现在,您的 products
Array
将包含所有 Price
和 Time
示例:
for product in products{
print("Time:",product.time)
print("Price:",product.price)
}
输出:
Time: 1
Price: 4000
Time: 2
Price: 4000
Time: 3
Price: 4000
注意:为了更好的理解,这是我的video系列关于JSON在swift解析4
var timeArray = [String]()
var priceArray = [String]()
if jsonResult.object(forKey:"Prices") as? NSArray != nil
{
let pricesArray = jsonResult.object(forKey:"Prices") as! NSArray
for i in 0..<self.pricesArray.count
{
// Getting Time
if jsonResult.object(forKey:"Time") as? Int != nil
{
self.timeArray.append(jsonResult.object(forKey:"Time") as! Int)
}
else
{
print("Time is not a intrger")
}
// Getting Price
if jsonResult.object(forKey:"Price") as? Int != nil
{
self.priceArray.append(jsonResult.object(forKey:"Price") as! Int)
}
else
{
print("Price is not a intrger")
}
}
}
else
{
print("Empty Array")
}
首先不要使用NSArray / NSDictionary
,使用原生Swift类型。
键 Prices
的值是 [String:Int]
个字典的数组:
if let jsonResult = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
let prices = jsonResult["Prices"] as? [[String:Int]] {
for price in prices {
print(price["Time"]!, price["Price"]!)
}
}
但是我建议将 JSON 解码成一个在 Swift 4
中非常简单的结构
struct Item : Decodable {
let hall : String
let date : Int
let prices : [Price]
private enum CodingKeys : String, CodingKey { case hall = "Hall", date = "Date", prices = "Prices"}
}
struct Price : Decodable {
let time, price : Int
private enum CodingKeys : String, CodingKey { case time = "Time", price = "Price"}
}
do {
let result = try JSONDecoder().decode(Item.self, from: data!)
print(result)
} catch { print(error) }
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any], let pirces = json["prices"] // checking json is formed well.
{
for price in prices { // iterating throught array that you received.
print (price["Price"])
}
}
我的 api
中有结构{
"Hall":"Hall",
"Date":20180501,
"Prices":[
{
"Time":1,
"Price":4000
},
{
"Time":2,
"Price":4000
},
{
"Time":3,
"Price":4000
}
]
}
现在卡住了,拉不出价格和时间。我明白了很多问题,但我还是不明白,请帮助。
我使用这个代码:
let url = URL(string: "http://<...>/api/prices?hall=<...>&date=20180501")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let err = error {
print(err)
} else {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
// ...
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
} catch {
print("error")
}
}
})
task.resume()
}
我是 json 的新手,刚开始学习它。我知道这很容易,但我想不通。我也知道我可以使用 codable 和 decodable,但现在我需要在这个实现中获得价格和时间。
产品结构:
struct Product{
let time:Int
let price:Int
init(_ object:[String:Int]){
self.time = object["Time"] ?? 0
self.price = object["Price"] ?? 0
}
}
Class变量:
var products = [Product]()
JSON 解析:
do{
if let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] {
//Use Swift dictionary instead of NSDictionary
if let prices = jsonObject["Prices"] as? [[String:Int]]{
for price in prices{
self.products.append(Product(price))
}
}
}
}catch{
print("Error: ",error.localizedDescription)
}
现在,您的 products
Array
将包含所有 Price
和 Time
示例:
for product in products{
print("Time:",product.time)
print("Price:",product.price)
}
输出:
Time: 1
Price: 4000
Time: 2
Price: 4000
Time: 3
Price: 4000
注意:为了更好的理解,这是我的video系列关于JSON在swift解析4
var timeArray = [String]()
var priceArray = [String]()
if jsonResult.object(forKey:"Prices") as? NSArray != nil
{
let pricesArray = jsonResult.object(forKey:"Prices") as! NSArray
for i in 0..<self.pricesArray.count
{
// Getting Time
if jsonResult.object(forKey:"Time") as? Int != nil
{
self.timeArray.append(jsonResult.object(forKey:"Time") as! Int)
}
else
{
print("Time is not a intrger")
}
// Getting Price
if jsonResult.object(forKey:"Price") as? Int != nil
{
self.priceArray.append(jsonResult.object(forKey:"Price") as! Int)
}
else
{
print("Price is not a intrger")
}
}
}
else
{
print("Empty Array")
}
首先不要使用NSArray / NSDictionary
,使用原生Swift类型。
键 Prices
的值是 [String:Int]
个字典的数组:
if let jsonResult = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
let prices = jsonResult["Prices"] as? [[String:Int]] {
for price in prices {
print(price["Time"]!, price["Price"]!)
}
}
但是我建议将 JSON 解码成一个在 Swift 4
中非常简单的结构struct Item : Decodable {
let hall : String
let date : Int
let prices : [Price]
private enum CodingKeys : String, CodingKey { case hall = "Hall", date = "Date", prices = "Prices"}
}
struct Price : Decodable {
let time, price : Int
private enum CodingKeys : String, CodingKey { case time = "Time", price = "Price"}
}
do {
let result = try JSONDecoder().decode(Item.self, from: data!)
print(result)
} catch { print(error) }
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any], let pirces = json["prices"] // checking json is formed well.
{
for price in prices { // iterating throught array that you received.
print (price["Price"])
}
}