How to parse the json data using swiftJson along with Alamofire

余生颓废 提交于 2019-12-01 10:52:42

Your json is already a SwiftyJSON object.

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

So to loop over the json you need for (_, entity) in json instead of for 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.

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.

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
    }
}

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)
}

Prints:

Optional("PIZZAS")
Optional(244)

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. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!