Devanan Devanan - 4 months ago 9
iOS Question

Swift: Help Regarding JSON Parsing

I am new to iOS programming and I have a small issue regarding JSON Parsing.

"data": [
{
"merchantId": "56a3285aa6579ac94739b1ae",
"timings": [
[
"11:00 AM",
"11:00 PM"
]
],
"tags": [
"buffet,fine dine,north indian,chinese,nagar,food,arabian,biryani"
],
"offers": [
{
"approvedBy": "56a07585d4490e07d9380a74",
"locationId": "56a5e2d8b57755b8b383d799",
"description": "Get 15% Flat Off on Minimum Bill of Rs. 450/-",
"finePrint": "• Cannot be combined with other offers.\n• Valid only for Dine-in & Take away.\n• Discount applicable on bill before taxes.\n• Taxes as applicable.",
"audience": "all",
"status": "live",
"createdAt": "2016-01-25T08:59:07.445Z",
"updatedAt": "2016-01-28T16:19:00.448Z",
"hangoutId": "",
"offerType": "PercentDiscountMin",
"discount": "15",
"amount": "450",
"maxDiscount": 0,
"id": "56a5e3dbb57755b8b383d79a"
},
{
"approvedBy": "56a07585d4490e07d9380a74",
"locationId": "56a5e2d8b57755b8b383d799",
"description": "Get 25% Off on Buffet Bill",
"finePrint": "• Cannot be combined with other offers.\n• Prior appointment/reservation is recommended.\n• Valid only for Dine-in.\n• Discount applicable on bill before taxes.\n• Taxes as applicable.",
"audience": "all",
"status": "live",
"createdAt": "2016-01-25T09:01:24.289Z",
"updatedAt": "2016-01-28T16:22:17.378Z",
"hangoutId": "",
"offerType": "PercentDiscount",
"discount": "25",
"amount": 0,
"maxDiscount": 0,
"id": "56a5e464b57755b8b383d79b"
},
{
"approvedBy": "56a07585d4490e07d9380a74",
"locationId": "56a5e2d8b57755b8b383d799",
"description": "Get 30 - 40% Off on Buffet Bill",
"finePrint": "• Valid only for Special Occasion \n• Cannot be combined with other offers.\n• Prior appointment/reservation is recommended.\n• Valid only for Dine-in.\n• Discount applicable on bill before taxes.\n• Taxes as applicable.",
"audience": "all",
"status": "live",
"createdAt": "2016-01-25T09:03:15.480Z",
"updatedAt": "2016-01-28T16:29:58.332Z",
"hangoutId": "",
"offerType": "PercentDiscount",
"discount": "30",
"amount": 0,
"maxDiscount": 0,
"id": "56a5e4d3b57755b8b383d79c"
}
};


I want to download the above JSON data, parse it and display it in a label.
I am able to download and display the merchantId by using the below code:

let JSONRespone = response.result.value as? [String:AnyObject]
if JSONRespone != nil {

let datarray = JSONRespone!["data"] as? [[String:AnyObject]]
if datarray != nil {
for data in datarray! {

let anObject = SomeObject()

let merchantId = data["merchantId"] as? String
if merchantId != nil {
anObject.merchantidentity = merchantId!
}


If I use the same code for the timings and tags, it is not displaying anything. when I try to display the result in the console, it displays "nil".

Apart from that how could I print the "description" in "offers" in three different labels. I could only print one among all of those.
Can someone please help me display the following. Thanks in advance.

Answer

note that offers is an array of offers, each item in the array is a dictionary, so you better create a new object "class" Offer, with properties that represent each key in each dictionary in offers array

so your SomeObject class should look something like

class SomeObject {

   var name: String!
   var imageURLString: String!
   var address: String!
   var area: String!
   var awardedLoyalty: Int!
   var cashbackPercentage: Double!
   var city: String!
   var contactNumber: String!
   var createdAt: String!
   var distanceFromUser: Double!
   var id: String!
   var isDiscounted: Bool!
   var isFavorite: Bool!
   var latitude: Double!
   var logo: String!
   var longitude: Double!
   var merchantId: String!
   var offers: [Offer]! // this is an array of offers, each offer in the array is of type (Offer()), which you must create your self, check Offer.swift file, it's a class Offer
   var tags: [String]!
   var timings: [String]!
   var updatedAt: String!

}

and SomeObject.offers is an array of Offer

so your Offer object "class" should be something like

class Offer {

    var amount: Double!
    var approvedBy: String!
    var audience: String!
    var createdAt: String!
    var description: String!
    var discount: Double!
    var finePrint: String!
    var hangoutId: String!
    var id: String!
    var locationId: String!
    var maxDiscount: Double!
    var offerType: String!
    var status: String!
    var updatedAt: String!
}

also note the tags is an array of strings, each string is some tags separated by "," Backend developer should make it an array of separate strings for each tag

however, here i add the code that completes your parsing part of your code

{

                    for data in dataArray! {

                        let anObject = SomeObject()

                        let name = data["name"] as? String
                        if name != nil {
                            anObject.name = name!
                            print("anObject.name \(name!)")
                        }

                        let heroImage = data["heroImage"] as? String
                        if heroImage != nil {
                            anObject.imageURLString = heroImage!
                            print("anObject.imageURLString \(heroImage!)")
                        }

                        let address = data["address"] as? String
                        if address != nil {
                            anObject.address = address!
                            print("anObject.address \(address!)")
                        }

                        let area = data["area"] as? String
                        if area != nil {
                            anObject.area = area!
                            print("anObject.area \(area!)")
                        }

                        let city = data["city"] as? String
                        if city != nil {
                            anObject.city = city!
                            print("anObject.city \(city!)")
                        }

                        let contactNumber = data["contactNumber"] as? String
                        if contactNumber != nil {
                            anObject.contactNumber = contactNumber!
                            print("anObject.contactNumber \(contactNumber!)")
                        }

                        let createdAt = data["createdAt"] as? String
                        if createdAt != nil {
                            anObject.createdAt = createdAt!
                            print("anObject.createdAt \(createdAt!)")
                        }

                        let distanceFromUser = data["distanceFromUser"] as? Double
                        if distanceFromUser != nil {
                            anObject.distanceFromUser = distanceFromUser!
                            print("anObject.distanceFromUser \(distanceFromUser!)")
                        }

                        let id = data["id"] as? String
                        if id != nil {
                            anObject.id = id!
                            print("anObject.id \(id!)")
                        }

                        let isDiscounted = data["isDiscounted"] as? Int
                        if isDiscounted != nil {
                            if isDiscounted! == 0 {
                                anObject.isDiscounted = false
                            }
                            else if isDiscounted == 1 {
                                anObject.isDiscounted = true
                            }
                            print("anObject.isDiscounted \(anObject.isDiscounted)")
                        }

                        let isFavorite = data["isFavorite"] as? Int
                        if isFavorite != nil {
                            if isFavorite! == 0 {
                                anObject.isFavorite = false
                            }
                            else if isFavorite == 1 {
                                anObject.isFavorite = true
                            }
                            print("anObject.isFavorite \(anObject.isFavorite)")
                        }


                        let latitude = data["latitude"] as? Double
                        if latitude != nil {
                            anObject.latitude = latitude!
                            print("anObject.latitude \(latitude!)")
                        }

                        let longitude = data["longitude"] as? Double
                        if longitude != nil {
                            anObject.longitude = longitude!
                            print("anObject.longitude \(longitude!)")
                        }

                        let merchantId = data["merchantId"] as? String
                        if merchantId != nil {
                            anObject.merchantId = merchantId!
                            print("anObject.merchantId \(merchantId!)")
                        }

                        let logo = data["logo"] as? String
                        if logo != nil {
                            anObject.logo = logo!
                            print("anObject.logo \(logo!)")
                        }

                        let awardedLoyalty = data["awardedLoyalty"] as? Int
                        if awardedLoyalty != nil {
                            anObject.awardedLoyalty = awardedLoyalty!
                            print(" anObject.awardedLoyalty \(awardedLoyalty!)")
                        }

                        let cashbackPercentage = data["cashbackPercentage"] as? Double
                        if cashbackPercentage != nil {
                            anObject.cashbackPercentage = cashbackPercentage!
                            print("anObject.cashbackPercentage \(cashbackPercentage!)")
                        }

                        let offers = data["offers"] as? [[String:AnyObject]]
                        if offers != nil {

                            var offersArray: [Offer] = []

                            for anOffer in offers! {
                                // note that offers is an array of offers, each item in the array is a dictionary, so you better create a new object Offer, with properties that represent each key in each dictionary in offers array
                                let offer = Offer()


                                let amount = anOffer["amount"] as? Double
                                if amount != nil {
                                    offer.amount = amount!
                                    print("offer.amount \(amount!)")
                                }

                                let approvedBy = anOffer["approvedBy"] as? String
                                if approvedBy != nil {
                                    offer.approvedBy = approvedBy!
                                    print("offer.approvedBy \(approvedBy!)")
                                }

                                let audience = anOffer["audience"] as? String
                                if audience != nil {
                                    offer.audience = audience!
                                    print("offer.audience \(audience!)")
                                }

                                let createdAt = anOffer["createdAt"] as? String
                                if createdAt != nil {
                                    offer.createdAt = createdAt!
                                    print("offer.createdAt \(createdAt!)")
                                }

                                let description = anOffer["description"] as? String
                                if description != nil {
                                    offer.description = description!
                                    print("offer.description \(description!)")
                                }

                                let discount = anOffer["discount"] as? Double
                                if discount != nil {
                                    offer.discount = discount!
                                    print("offer.discount \(discount!)")
                                }

                                let finePrint = anOffer["finePrint"] as? String
                                if finePrint != nil {
                                    offer.finePrint = finePrint!
                                    print("offer.finePrint \(finePrint!)")
                                }

                                let hangoutId = anOffer["hangoutId"] as? String
                                if hangoutId != nil {
                                    offer.hangoutId = hangoutId!
                                    print("offer.hangoutId \(hangoutId!)")
                                }

                                let id = anOffer["id"] as? String
                                if id != nil {
                                    offer.id = id!
                                    print("offer.id \(id!)")
                                }

                                let locationId = anOffer["locationId"] as? String
                                if locationId != nil {
                                    offer.locationId = locationId!
                                    print("offer.locationId \(locationId!)")
                                }

                                let maxDiscount = anOffer["maxDiscount"] as? Double
                                if maxDiscount != nil {
                                    offer.maxDiscount = maxDiscount!
                                    print("offer.maxDiscount \(maxDiscount!)")
                                }

                                let offerType = anOffer["offerType"] as? String
                                if offerType != nil {
                                    offer.offerType = offerType!
                                    print("offer.offerType \(offerType!)")
                                }

                                let status = anOffer["status"] as? String
                                if status != nil {
                                    offer.status = status!
                                    print("offer.status \(status!)")
                                }

                                let updatedAt = anOffer["updatedAt"] as? String
                                if updatedAt != nil {
                                    offer.updatedAt = updatedAt!
                                    print("offer.updatedAt \(updatedAt!)")
                                }

                                offersArray.append(offer)
                            }

                            anObject.offers = offersArray
                        }


                        let tags = data["tags"] as? [String]
                        for tag in tags! {
                            //note the tags array of strings, each string is some tags separated by ","
                            //backend developer should make it an array of separate string for each tag
                            let tagsArray = tag.componentsSeparatedByString(",")
                            anObject.tags = tagsArray
                            print("tagsArray \(tagsArray)")
                        }

                        let timings = data["timings"] as? [[String]]
                        if timings != nil {

                            for timingsArray in timings! {
                                var aTimingArray: [String] = []

                                for timing in timingsArray {

                                    aTimingArray.append(timing)
                                    print("timing \(timing)")
                                }
                                anObject.timings = aTimingArray
                            }


                        }


                        let updatedAt = data["updatedAt"] as? String
                        if updatedAt != nil {
                            anObject.updatedAt = updatedAt!
                            print("anObject.updatedAt \(updatedAt!)")
                        }