ios - Swift:有关 JSON 解析的帮助

标签 ios json swift xcode

我是 iOS 编程新手,有一个关于 JSON 解析的小问题。

"data": [
{
  "merchantId": "56",
"timings": [
    [
      "11:00 AM",
      "11:00 PM"
    ]
  ],
"tags": [
    "dine,north chinese"
  ],
"offers": [
    {
      "approvedBy": "56",
      "locationId": "56",
      "description": "Get 15% Off",
      "finePrint": "• Cannot be combined with other offers.",
      "audience": "all",
      "status": "live",
      "createdAt": "2016",
      "updatedAt": "2016",
      "offerType": "Discount",
      "discount": "15",
      "maxDiscount": 0,
      "id": "56"
    },
    {
      "approvedBy": "56023",
      "locationId": "56023",
      "description": "Get 25% Off",
      "finePrint": "• Cannot be combined with other offers",
      "audience": "all",
      "status": "live",
      "createdAt": "2016",
      "updatedAt": "2016",
      "hangoutId": "",
      "offerType": "PercentDiscount",
      "discount": "25",
      "amount": 0,
      "maxDiscount": 0,
      "id": "5623"
    },
};

我想下载上面的JSON数据,解析它并将其显示在标签中。 我可以使用以下代码下载并显示merchantId:

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

如果我对计时和标签使用相同的代码,它不会显示任何内容。当我尝试在控制台中显示结果时,它显示“nil”。

除此之外,我如何在三个不同的标签中打印“优惠”中的“描述”。我只能打印其中的一张。 有人可以帮我显示以下内容吗?提前致谢。

最佳答案

注意,offers是一个offers数组,数组中的每一项都是一个字典,所以你最好创建一个新的对象“class”Offer,其属性代表offers数组中每个字典中的每个键

所以你的 SomeObject 类应该看起来像这样

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!

}

而SomeObject.offers是Offer数组

所以你的 Offer 对象“类”应该类似于

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

还要注意标签是一个字符串数组,每个字符串都是一些用“,”分隔的标签 后端开发人员应该将其设置为每个标签的单独字符串数组

但是,这里我添加了完成代码解析部分的代码

{

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

关于ios - Swift:有关 JSON 解析的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38533165/

相关文章:

ios - NSPointerArray 基础知识

javascript - 由于 JSON 中的转义单引号,jQuery.parseJSON 抛出 “Invalid JSON” 错误

javascript - 如何将变量保存到 JSON 文件?

java - 如何从 jsonArray 获取相同的字段

ios - 如何防止导航到 UIViewController 检查条件?

swift - 在 Swift 中获取 ForceFeedback 设备

ios - Google Maps iOS SDK - 在 subview 中添加 GMSPanoramaView

ios - 如何在不为每种语言创建 xib 的情况下本地化 xib View 中的文本?

ios - UITableViewCell 中的 UIButton 问题 : can't get recognized selector

ios - 删除和添加相同插件后的 Cordova 构建错误