Reputation: 193
I am trying to read a locally declared JSON, since I still do not have the network ready to send me JSON examples for the app we are developing. For some reason I get a null when trying to print the json created by SwiftyJSON framework. This is my class:
import Foundation
import SwiftyJSON
let mockShifts = "{\"numOfShiftsInDay\": 3,\"shifts\": [{\"StartTime\": \"06:30\",\"EndTime\": \"14:00\"},{\"StartTime\": \"14:00\",\"EndTime\": \"19:00},{\"StartTime\": \"19:00\",\"EndTime\":\"01:00\"}]}"
class WeeklySchedule {
var shifts: [Shift] = []
var shiftsAmount: Int = 3
var relative: Int = 0
func setShiftsAmount(amount: Int){
self.shiftsAmount = amount
for _ in 1...amount{
self.shifts.append(Shift())
}
getShifts()
}
func getRelative() -> Int{
return relative
}
func getShifts(){
let data = mockShifts.data(using: .utf8)!
let json = JSON(data: data)
print(mockShifts) //This prints out a JSON that looks OK to me
print(json) //This prints NULL
if let numOfShifts = json["numOfShiftsInDay"].string {
print(numOfShifts) //This code is unreachable
}
}
}
And this is my console output, when calling setShiftsAmount()
which calls getShifts()
:
{"numOfShiftsInDay": 3,"shifts": [{"StartTime": "06:30","EndTime": "14:00"},{"StartTime": "14:00","EndTime": "19:00},{"StartTime": "19:00","EndTime":"01:00"}]}
null
Why is my JSON null?
Upvotes: 0
Views: 62
Reputation: 72410
The reason you are getting null for your JSON
because your JSON
string mockShifts
is not contain's valid JSON
, there is missing double quote(\")
for the EndTime
key after 19:00
in the second object of array shifts. Add that double quote and you all set to go.
let mockShifts = "{\"numOfShiftsInDay\": 3,\"shifts\": [{\"StartTime\": \"06:30\",\"EndTime\": \"14:00\"},{\"StartTime\": \"14:00\",\"EndTime\": \"19:00\"},{\"StartTime\": \"19:00\",\"EndTime\":\"01:00\"}]}"
Upvotes: 2