【问题标题】:JSONSerialization formattingJSON序列化格式
【发布时间】:2020-01-30 13:31:16
【问题描述】:

我需要有关 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" },
    ]
}

有人可以帮我用这段代码得到正确的结果吗?

【问题讨论】:

  • 您正在为站创建一个对象,而不是为站插入一个对象的数组

标签: json swift json-serialization


【解决方案1】:

使用 2 个方括号为站创建一个对象数组。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2015-11-02
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多