Jaco2201
Jaco2201

Reputation: 125

Convert Parse.com json array into Array with swift

Can someone please help me with this. I saved my data into Parse.com into column with type array (example: ["11:30","12:45,"13:02"], just some list of some times as string). I have tried to get this data with swift:

var take: NSMutableArray!

var query = PFQuery(className: "test")
query.getObjectInBackgroundWithId("QZ6Y8Oljc5"){
   (testData: PFObject!, error: NSError!) -> Void in
      if (error == nil){
         take = testData["workday"]
         println(take)    
       }
       else{
         println(error)
        }
}

the problem is that i get only json array type:

(
   "11:30",
   "12:45,
   "13:02"
)

How can I convert it into NSArray so it could be like:

var myArray =  ["11:30","12:45,"13:02"]

Thank you for any suggestions because I tried every method I found here, but without any results.

Upvotes: 1

Views: 1620

Answers (1)

Andrew Aquino
Andrew Aquino

Reputation: 42

The problem with JSON data is that it is it's own array that has to be sifted and groomed. normally people would end up using huge nested IF statements which ends up looking messy. Luckily, someone created a code that sifts through JSON data and gives you back usable types (Int, Arrays, Strings) by use of a massive switch table.

https://github.com/SwiftyJSON/SwiftyJSON

Look it up, it should help. Once you have it implemented you can call it by typing..

let json = JSON(Data : JSONData)

then to sift through, you use substrings.. (depending on the data, you match it with a string or int)

let firstIndex = json["workday"]

//Int
let firstIndexOfWorkDay = json["workday"][0]

//String
let firstIndexOfWorkDay = json["workday"]["time"]

and so on... however, you will need to cast it once you singled out the data

let firstIndexOfWorkDay = json["workday"][0].valueOfFloat

//printing it would give 11:30

although personally I use ".description" .. since sometimes when I sift through all the array, its a mix of types.

let firstIndexOfWorkDay = json["workday"][0].description

println(firstIndexOfWorkDay)

//would literally give "11:30" including the quotation marks

then I use string methods to trim the quotations then cast it to whatever type I need. But it's up to your creativity once you figure out how it works

Upvotes: 1

Related Questions