Reputation: 2743
I am trying to loop through a json and place each item into its own array. I don't know how to loop though the json though.I have successfully went though and placed the json once and filled the array, but now I need the whole json into the respected arrays. Any help will be appreciated
Here is what I got:
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)
}
And the Json I want to parse will look like this
[
{
"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
]
Upvotes: 0
Views: 1753
Reputation: 285082
Swift is an object oriented language, so create a custom object rather than using a bunch of unrelated arrays.
struct Coupon {
var name : String
var description : String
var amount : Int
var type : String
var startDate : String
var endDate : String
var barcode : String
}
In parseCoupons
use Swift native collection types, the method returns the parsed Coupon
items:
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
}
Side note: Your do - catch
block is meaningless, the good code must be within the do
scope and executing the expression myJson[item]as! NSDictionary)
again and again in the repeat loop is very inefficient.
Edit
In Swift 4 it became much more convenient.
Adopt Decodable
struct Coupon : Decodable { ...
and enjoy the magic of the 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)
}
Upvotes: 3
Reputation: 2743
I got it working by adjusting and playing with the code it works. The for loop structure is very important other wise it won't work just right.
for i in 0..<myJson.count
{
titleArray.append((myJson[i]as! NSDictionary)["name"] as! String)
descriptionArray.append((myJson[i]as! NSDictionary)["description"] as! String)
amountArray.append((myJson[i]as! NSDictionary)["amount"] as! Int)
typeArray.append((myJson[i]as! NSDictionary)["type"] as! String)
startDateArray.append((myJson[i]as! NSDictionary)["start_date"] as! String)
endDateArray.append((myJson[i]as! NSDictionary)["end_date"] as! String)
barcodeArray.append((myJson[i]as! NSDictionary)["barcode"] as! String)
}
Its very similar to your @Nirav so thanks for leading me to this
Upvotes: 0
Reputation: 72420
Instead of creating multiple array
create on which contain Dictionary
like this.
var arr : [NSDictionary] = [NSDictionary]()
Now add all your object in this array like this
for item in myJson.count {
arr.append(myJson[item] as! NSDictionary)
}
Now you can access each element using dictionary of this array like this
print((arr[0] as! NSDictionary)["name"] as! String)
Hope this will help you.
Upvotes: 1