【发布时间】:2015-06-04 17:02:36
【问题描述】:
我从以前的开发人员那里挑选了一个项目,结果有点乱。我们已经转移到一个结构更好的新 API,我很困惑如何让它工作。
我有一个 API,我正在尝试从中解析数据,因此它是可用的形式,而且我足够新,可以使用一些帮助。
有人可以看看下面的代码并指导我并解释这里发生了什么,也许如何让它正常工作?这几天我一直在用头撞墙。
这是我收到的 JSON 响应示例:
{
“Green Shirt": [
{
"id": "740",
"name": “Nice Green Shirt",
"quantity": "0",
"make": "",
"model": "",
"price": “15.00",
"size": "XXS",
"sku": null,
"image": "https:\/\/google.com\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
},
{
"id": "743",
"name": "Green Shirt",
"quantity": “68",
"make": "",
"model": "",
"price": “20.00",
"size": "XS",
"sku": null,
"image": "https:\/\/google.com\/green_shirt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
}
],
“Dark Blue Jeans": [
{
"id": "1588",
"name": "Dark Blue Jeans",
"quantity": "0",
"make": "",
"model": "",
"price": "0.00",
"size": “S",
"sku": null,
"image": "https:\/\/google.com\/dark_blue_jeans.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
},
{
"id": "1559",
"name": "Dark Blue Jeans",
"quantity": "4",
"make": "",
"model": "",
"price": "0.00",
"size": “XL",
"sku": null,
"image": "https:\/\/google.com\/dark_blue_jeans.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
}
],
“White Belt": [
{
"id": "1536",
"name": "White Belt",
"quantity": "37",
"make": "",
"model": "",
"price": "0.00",
"size": "One Size",
"sku": null,
"image": "https:\/\/google.com\/white_belt.jpg",
"new_record": false,
"category_name": "",
"bar_code": "",
"category": null
}
]
}
应该接受 JSON 响应的类
public class Inventory {
public var products = [Product]()
public init(type: Product.Type, data:[[String:AnyObject]]) {
for productData in data {
products.append(type(data: productData))
}
}
}
产品类别
public class Product {
public var data:[String:AnyObject]
required public init(data: [String:AnyObject]) {
self.data = data
}
}
主要产品类别
class MainProduct : Product {
var id:String? {
return data["id"] as? String
}
var name:String {
return data["model"] as! String
}
var sizes:[String:Int] {
if let items = data["quantities"] as? [String:Int] {
return items
} else {
return [String:Int]()
}
}
var upc :String? {
return data["UPC"] as? String
}
var price:Double {
if let price = data["price"] as? Double {
return price
} else if let price = data["price"] as? NSString {
return price.doubleValue
} else {
fatalError("Did not get a price")
}
}
}
【问题讨论】:
-
您在解析 json 响应时实际上遇到了麻烦?
-
请说明您的问题。你有任何错误信息吗?代码编译了吗?
-
没有遇到响应问题,只是新手不知道如何使这些类与新的 API 响应一起工作。希望这是有道理的。尽管这一天我真的一直在工作。我觉得如果我得到一些帮助来了解这些如何协同工作,就足以让我在更深层次上理解这一切。
标签: json swift nsdictionary