如何使用swiftJson和Alamofire解析json数据 [英] How to parse the json data using swiftJson along with Alamofire

查看:421
本文介绍了如何使用swiftJson和Alamofire解析json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Json数据样本.这只是一个数据样本.同样,可用的数据也很多,例如子类别数是22.根据子类别,项数也有所不同.行数也是15,其中名字是Pizza.

my Json data sample. this is only a sample of data .Likewise so much data available like number of subcategory is 22. number of items are different according to subcategory.Also number of rows are 15 in which the first name is Pizza.

[
 {
  "id": "244",
  "name": "PIZZAS",
  "image": "",
  "coupon": "1",
  "icon": "",
  "order": "1",
  "aname": "",
  "options": "2",
  "subcategory": [
              {
                "id": "515",
                "name": "MARGARITA",
                "description": "Cheese and Tomato",
                "image": "",
                "icon": "",
                "coupon": "1",
                "order": "1",
                "aname": "",
                "options": "2",
                "item": [
                            {
                               "id": "1749",
                               "name": "9 Inch Thin & Crispy Margarita",
                               "description": "",
                               "price": "3.40",
                               "coupon": "1",
                               "image": "",
                               "options": "2",
                               "order": "1",
                               "addon": "495",
                               "aname": "",
                               "icon": ""
                        }]
          }]
  }]

我想将所有名称,所有子类别名称,所有项目名称和所有项目描述都提取到特定数组中,以便我可以特别填充到不同的表视图中

I want to fetch the all name, all subcategory name, all item name and all item description into particular array so that i can populate particularly into different tableview

func ParseJSON(){
     var MenuList = [Menu]()

    Alamofire.request(.GET, myUrl)
        .validate()
        .responseJSON { response in
            switch response.result
            {
            case .Success:
                if let value = response.result.value {
                    let json = JSON(value)
                     print("JSON: \(json)")
                      for entity in json{
                        print(entity)
                       MenuList.append(entity["name"])  ///error
                    }

                }
            case .Failure(let error):
                print(error)
            }
    }

}

我能够使用Alamofire来获取响应.现在如何使用swiftJson实现它?

I am able to fetch the response using Alamofire. Now How to implement it using swiftJson ??

已更新

我为主要类别,子类别和项目添加了类模型.

I have added the class model for main category, subcategory and items.

    import UIKit
    class Menu {
                 var id: Int?
                 var name: String?
                 var image: UIImage?
                 var coupon: Int?
                 var icon: UIImage?
                 var order: Int?
                 var aname: Int?
                 var options: Int?

init(id:Int,name:String,image:UIImage,coupon:Int,icon:UIImage,order:Int,aname:Int,options:Int){
        self.id = id
        self.name = name
        self.image = image
        self.coupon = coupon
        self.icon = icon
        self.order = order
        self.aname = aname
        self.options = options


    }
   }

如何将数据传递给类并获取值

how to pass the data to the class and get the value

推荐答案

您的json已经是一个SwiftyJSON对象.

Your json is already a SwiftyJSON object.

这些对象始终具有索引键和内容键.

These objects always have an index key and a content key.

因此要遍历json,您需要for (_, entity) in json而不是for entity in json.

So to loop over the json you need for (_, entity) in json instead of for entity in json.

_部分是我们忽略的索引.如果我们想使用索引,也可以执行for (index, entity) in json.

The _ part is the index that we ignore. We could also do for (index, entity) in json if we wanted to use the index.

您还需要使用SwiftyJSON的类型属性,例如.string(可选)或.stringValue(非可选).

You also need to use SwiftyJSON's type properties, like .string (optional) or .stringValue (non optional).

在模型类中,属性类型必须反映您获得的属性.

In your model class, the properties types have to reflect the ones you get.

要从JSON的第一级填充Menu对象的数组,可以像这样修改模型:

To populate an array of Menu objects from the first level of your JSON, you could adapt your model like this:

class Menu {
    var id: Int?
    var name: String?
    var image: String?
    var coupon: Int?
    var icon: String?
    var order: Int?
    var aname: String?
    var options: Int?

    init(id: Int?, name: String?, image: String?, coupon: Int?, icon: String?, order: Int?, aname: String?, options: Int?) {
        self.id = id
        self.name = name
        self.image = image
        self.coupon = coupon
        self.icon = icon
        self.order = order
        self.aname = aname
        self.options = options
    }
}

然后从JSON填充数组:

Then populate an array from the JSON:

var menus = [Menu]()

for (_, content) in json {
    let menu = Menu(id: Int(content["id"].stringValue),
                    name: content["name"].string,
                    image: content["image"].string,
                    coupon: content["coupon"].int,
                    icon: content["icon"].string,
                    order: Int(content["order"].stringValue),
                    aname: content["name"].string,
                    options: Int(content["options"].stringValue))
    menus.append(menu)
}

现在,您可以根据需要遍历对象:

Now you can iterate over your objects as you need:

for menu in menus {
    print(menu.name)
    print(menu.id)
}

打印:

可选("PIZZAS")
可选(244)

Optional("PIZZAS")
Optional(244)

现在,如果您还想使用每个对象的子类别"中的数据,则必须制作反映这些属性的其他模型类,例如"SubCategory"类和"Item"类(这些也可以是例如存储在每个菜单中).而且,您使用与我的示例相同的系统来填充它们-您只需要适应每种格式,但是现在有了这个有效的示例,到达那里应该很简单.诀窍是充分了解您的JSON结构,以便您可以在模型对象中反映它.主要集中于此,其余将接follow而至. :)

Now if you want to also use the data in the "subcategory" of each object, you have to make other model classes which reflect these properties, like a "SubCategory" class and an "Item" class (those could be also stored in each Menu, for example). And you use the same system as my example to populate them - you just have to adapt to each format, but now that you have this working example it should be rather simple to get there. The trick is to understand your JSON structure well enough so that you can reflect it in your model objects. Focus primarily on this and the rest will follow. :)

这篇关于如何使用swiftJson和Alamofire解析json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆