Swift:关于 JSON 解析的帮助
Posted
技术标签:
【中文标题】Swift:关于 JSON 解析的帮助【英文标题】:Swift: Help Regarding JSON Parsing 【发布时间】:2016-07-22 18:30:27 【问题描述】:我是 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 数据,解析它并显示在标签中。 我可以使用以下代码下载并显示商家 ID:
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”。
除此之外,我如何在三个不同的标签中打印“优惠”中的“描述”。我只能打印所有这些中的一个。 有人可以帮我显示以下内容。提前致谢。
【问题讨论】:
【参考方案1】:注意offers是一个offers数组,数组中的每个item都是一个字典,所以你最好创建一个新的对象“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!)")
【讨论】:
【参考方案2】:merchantId
是字符串值的键,timings
和 tags
是数组的键,因此您可以使用下标或 .firstObject
/.lastObject
调用进入数组:
swift
let timing: String = data["timings"][0] as? String
另外,SwiftyJSON 是一个很棒的 Cocoapod,用于在访问 JSON 值时减少对选项的使用
【讨论】:
我已经编辑了我的问题。您能否查看我添加的部分,即我添加的“优惠”部分,并帮助我如何取得进展。谢谢。offers
是一个字典数组,因此在为数组下标后,您需要使用所需值的键(字符串)为字典下标。 let offerId: String = data["offers"][0]["id"] as? String
我添加了上面的代码并尝试运行该应用程序。当我运行应用程序时,应用程序崩溃并且我收到一条错误消息,提示“无法将类型 '__NSCFArray' (0x1059a7d68) 的值转换为 'NSString' (0x106467b48)”。当我尝试“标签”时,我得到了相同的响应。
尝试data[0]["timings"][0]
看起来数据是具有一个字典的字典数组的键。说真的,使用 SwiftyJSON。如果你解析错误,它只会返回nil
而不是崩溃
而 Timings 看起来特别像一个数组数组......所以data[0]["timings"][0][0] as? String
【参考方案3】:
是的,您可以使用 if let 语句进行 for 循环和迭代。
否则你 swiftyJson 并在 2-3 行中执行此操作。我建议这样做,但作为初学者,您可以尝试使用循环进行解析。
因为通常当您从互联网上的任何 json 文件中解析数据时。使用AnyObject
,因为您不知道类型,然后再进行转换。
【讨论】:
以上是关于Swift:关于 JSON 解析的帮助的主要内容,如果未能解决你的问题,请参考以下文章