快速解析json
Posted
技术标签:
【中文标题】快速解析json【英文标题】:json parsing in swift 【发布时间】:2015-03-03 09:07:33 【问题描述】:这是我的 Json
"id": "63",
"name": "Magnet",
"price": "₹1250",
"description": "",
"image": [
"catalog/IMG-20150119-WA0012_azw1e3ge.jpg",
"catalog/IMG-20150119-WA0029_6mr3ndda.jpg",
"catalog/IMG-20150119-WA0028_ooc2ea52.jpg",
"catalog/IMG-20150119-WA0026_4wjz5882.jpg",
"catalog/IMG-20150119-WA0024_e38xvczi.jpg",
"catalog/IMG-20150119-WA0020_vyzhfkvf.jpg",
"catalog/IMG-20150119-WA0018_u686bmde.jpg",
"catalog/IMG-20150119-WA0016_c8ffp19i.jpg"
],
"thumb_image": [
"cache/catalog/IMG-20150119-WA0012_azw1e3ge-300x412.jpg",
"cache/catalog/IMG-20150119-WA0029_6mr3ndda-300x412.jpg",
"cache/catalog/IMG-20150119-WA0028_ooc2ea52-300x412.jpg",
"cache/catalog/IMG-20150119-WA0026_4wjz5882-300x412.jpg",
"cache/catalog/IMG-20150119-WA0024_e38xvczi-300x412.jpg",
"cache/catalog/IMG-20150119-WA0020_vyzhfkvf-300x412.jpg",
"cache/catalog/IMG-20150119-WA0018_u686bmde-300x412.jpg",
"cache/catalog/IMG-20150119-WA0016_c8ffp19i-300x412.jpg"
],
"specifications": [
"Fabrics": [
"Pure chiffon straight cut suits 48" length"
]
,
"MOQ": [
"Minimum 10"
]
]
在上面的 json 字符串中,“规范”数组列表有动态的键数,每个键都有动态的值数
那么如何解析呢?如果有人知道,请帮忙...
提前致谢
【问题讨论】:
我的回答对你有帮助吗? 【参考方案1】:有多种方法可以进行解析。在您的情况下,specifications
应该是一个数组,因此您将能够循环每个项目。
你可能想要:
创建您自己的 JSON 解析类/方法; 使用现有的库来解析 JSON。对于第二个选项,您可以查看以下内容: https://github.com/Wolg/awesome-swift#jsonxml-manipulation
【讨论】:
【参考方案2】:var yourJson = data as? NSDictionary
if let id = yourJson.valueForKey("id") as String
//save your id from json
if let name = yourJson.valueForKey("name") as String
//save your name
...
if let images = yourJson.valueForKey("image") as NSArray
for im in images
//save image
//the same for all othe images
...等等...
您还应该观看一些教程,以了解 JSON 解析的基础知识..
https://www.youtube.com/watch?v=MtcscjMxxq4
【讨论】:
以上是关于快速解析json的主要内容,如果未能解决你的问题,请参考以下文章