JSONSerialization форматирование - PullRequest
1 голос
/ 30 января 2020

Мне нужна помощь с форматированием JSONSerialization.

  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)
        }

    }

И я получаю с этим:

{
  "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"
  }
}

Но мне нужно получить:

{
    "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" },
    ]
}

Может кто-нибудь помочь мне с этим кодом, чтобы получить правильный результат?

1 Ответ

1 голос
/ 30 января 2020

Используйте 2 квадратных скобки для создания массива объекта для станции.

let stations = ["station":[["name": "\(currentStation.name)", "desc": "\(currentStation.desc)", "longDesc": "\(currentStation.longDesc)", "imageURL": "\(currentStation.imageURL)", "streamURL": "\(currentStation.streamURL)"]]]

...