I need help with JSONSerialization formatting.
func saveToJsonFile() {
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("Radios.json")
let stations = ["station":["name": "\(currentStation.name)", "desc": "\(currentStation.desc)", "longDesc": "\(currentStation.longDesc)", "imageURL": "\(currentStation.imageURL)", "streamURL": "\(currentStation.streamURL)"]]
do {
let data = try JSONSerialization.data(withJSONObject: stations, options: .prettyPrinted)
try data.write(to: fileUrl, options: [])
} catch {
print(error)
}
}
And I get with it:
{
"station" : {
"streamURL" : "http:\/\/s9.viastreaming.net:9565\/;stream.nsv",
"name" : "94.1FM Gold Coast Radio",
"longDesc" : "94.1FM is a Gold Coast Community Radio Station offering a music format catering for today's up and at it senior generation. With new music and valued memories by original artist and also many of today's new performers. The station also offers LIVE up to date reports for Boating, Surfing and Traffic during Breakfast and Drive.",
"desc" : " 80s, 70s, 60s, entertainment, hits, community",
"imageURL" : "26613.v5.png"
}
}
But I need to get:
{
"station": [
{ "name": "2SM", "streamURL": "http://144.140.228.109:8220/mp3", "imageURL": "231.v15.png", "desc": " news, talk, sports, entertainment", "longDesc": "2SM news network - latest news and shows. Breakfast with Grant Goldman. Weekdays 5-9am on Sydney's 2SM 1269AM and the Super Network" },
]
}
Can somebody help me with this code to get the right result?
Use 2 square brackets to create an array of object for station.
let stations = ["station":[["name": "\(currentStation.name)", "desc": "\(currentStation.desc)", "longDesc": "\(currentStation.longDesc)", "imageURL": "\(currentStation.imageURL)", "streamURL": "\(currentStation.streamURL)"]]]