gpt4 book ai didi

ios - 循环遍历一个 json 文件并填充一个数组 Swift

转载 作者:行者123 更新时间:2023-11-28 10:18:31 24 4
gpt4 key购买 nike

我正在尝试遍历 json 并将每个项目放入其自己的数组中。我不知道如何循环遍历 json。我已经成功地遍历并放置了 json 一次并填充了数组,但现在我需要将整个 json 放入受尊重的数组中。任何帮助将不胜感激

这是我得到的:

func parseCoupons(response : String)
{
print("Starting to parse the file")
let data = response.dataUsingEncoding(NSUTF8StringEncoding)
var myJson : NSArray
myJson = []

do {
myJson = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
}
catch {
print("Error")
}

for item in myJson.count {
titleArray.append((myJson[item]as! NSDictionary)["name"] as! String)
descriptionArray.append((myJson[item]as! NSDictionary)["description"] as! String)
amountArray.append((myJson[item]as! NSDictionary)["amount"] as! Int)
typeArray.append((myJson[item]as! NSDictionary)["type"] as! String)
startDateArray.append((myJson[item]as! NSDictionary)["start_date"] as! String)
endDateArray.append((myJson[item]as! NSDictionary)["end_date"] as! String)
barcodeArray.append((myJson[item]as! NSDictionary)["barcode"] as! String)
}

我要解析的 Json 看起来像这样

[
{
"name": "Coupon Title",
"description": "The Coupon Description",
"type": "PERCENT_OFF",
"amount": 15,
"barcode": "4948473",
"start_date": "2016-12-01",
"end_date": "2016-12-25",

},

ECT ECT ECT

]

最佳答案

Swift 是一种面向对象的语言,因此创建一个自定义对象而不是使用一堆不相关的数组。

struct Coupon {

var name : String
var description : String
var amount : Int
var type : String
var startDate : String
var endDate : String
var barcode : String

}

parseCoupons中使用Swift原生集合类型,该方法返回解析后的Coupon项:

func parseCoupons(response : String) -> [Coupon]
{
print("Starting to parse the file")
let data = Data(response.utf8)
var coupons = [Coupon]()

do {
let myJson = try JSONSerialization.jsonObject(with: data) as! [[String:Any]]

for item in myJson {
let name = item["name"] as! String
let description = item["description"] as! String
let amount = item["amount"] as! Int
let type = item["type"] as! String
let startDate = item["start_date"] as! String
let endDate = item ["end_date"] as! String
let barcode = item["barcode"] as! String
let coupon = Coupon(name: name,
description: description,
amount: amount,
type: type,
startDate: startDate,
endDate: endDate,
barcode: barcode)
coupons.append(coupon)
}
} catch {
print("Error", error)
}
return coupons
}

旁注:您的 do - catch block 没有意义,好的 代码必须在 do 范围内并执行表达式 myJson[项目]as! NSDictionary) 在重复循环中一次又一次效率很低。

编辑

在 Swift 4 中,它变得更加方便。

采用可解码

struct Coupon : Decodable { ...

并享受协议(protocol)的魔力

func parseCoupons(response : String) throws -> [Coupon]
{
print("Starting to parse the file")
let data = Data(response.utf8)

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try decoder.decode([Coupon].self, from: data)
}

关于ios - 循环遍历一个 json 文件并填充一个数组 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38261020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com