【发布时间】:2017-04-28 06:01:36
【问题描述】:
我正在尝试解析一些 json 数据,但我正在努力理解如何提取和分配嵌套值。我可以管理第一级,但当它更进一步时,我会挣扎。
我有一个 parseProductsData 函数,它接收数据并与第一级嵌套一起正常工作。 我如何解析 [“Options”: “values”],[“variants”] 的嵌套 Json 数组。
这是我的 Json。
{
products: [
{
id: 8931647873,
title: "A bug Life1123",
body_html: "
Ban neckline
Printed front
Full sleeves
Straight hem
Printed back
100% khaddar shirt without embroidery
",
vendor: "Sapphire",
product_type: "Configurable Products",
created_at: "2017-03-01T23:54:41+05:00",
handle: "a-bug-life",
updated_at: "2017-03-17T16:30:46+05:00",
published_at: "2017-01-07T12:33:00+05:00",
template_suffix: "",
published_scope: "global",
tags: "Khaddar, L, M, Women, XL, Yellow",
variants: [...],
options: [
{
id: 10702667329,
product_id: 8931647873,
name: "Size",
position: 1,
values: [
"XXS",
"S",
"M",
"L",
"XL",
"XXL"
]
},
{
id: 10702667393,
product_id: 8931647873,
name: "Color",
position: 2,
values: [
"Yellow"
]
}
],
images: [
{
id: 20808811009,
product_id: 8931647873,
position: 1,
created_at: "2017-03-01T23:54:41+05:00",
updated_at: "2017-03-01T23:54:41+05:00",
src: "https://cdn.shopify.com/s/files/1/1814/9759/products/a_bugs_life.jpg?v=1488394481",
variant_ids: []
},
{
id: 20808811073,
product_id: 8931647873,
position: 2,
created_at: "2017-03-01T23:54:41+05:00",
updated_at: "2017-03-01T23:54:41+05:00",
src: "https://cdn.shopify.com/s/files/1/1814/9759/products/a_bugs_life..jpg?v=1488394481",
variant_ids: []
},
{
id: 20808811137,
product_id: 8931647873,
position: 3,
created_at: "2017-03-01T23:54:41+05:00",
updated_at: "2017-03-01T23:54:41+05:00",
src: "https://cdn.shopify.com/s/files/1/1814/9759/products/a_bugs_life.__2.jpg?v=1488394481",
variant_ids: []
}
],
image: {...}
},
func parseProductsData() {
Alamofire.request(BASE_URL+"/admin/products.json").responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let list = dict["products"] as? [Dictionary<String, AnyObject>] {
for i in 0..<list.count {
print(list[i])
}
}
}
}
}
【问题讨论】:
-
你可以使用swiftyjson
-
我正在其他功能中使用。加内什库马尔
-
但面临同样的问题:)
-
您可以ObjectMapper,而不是手动获取所有值。 Here 你可以找到嵌套数据的例子。
-
@GaneshKumar 你能解释一下吗? swiftyJson是如何解析的?