【问题标题】:write to file in swift 3 transforming the data from json to xml在swift 3中写入文件将数据从json转换为xml
【发布时间】:2017-05-15 12:31:11
【问题描述】:

注意下面的猫是从服务器返回的json类型,当我使用try! cats?.write(toFile: file, atomically: false) 该文件包含一个xml输出,而我需要保持为json,非常感谢任何帮助!

let text = ""
try! text.write(toFile: file, atomically: false, encoding: String.Encoding.utf8)

let parameters : NSMutableDictionary? = [`enter code here`]

let manager = AFHTTPSessionManager()

manager.post("http://appsandgamesinc.com/api/AppAsUser/getMedias/", parameters: parameters, progress: nil, success: { (task: URLSessionTask, responseObject) in
      let response = responseObject as? NSDictionary
      let medias = response?.object(forKey: "medias") as? NSDictionary

      let cats = medias as? NSDictionary
      print("cats:\(cats)")
NSKeyedArchiver.archivedData(withRootObject: medias)

      try! cats?.write(toFile: file, atomically: false)

      print("file://"+file)
})

【问题讨论】:

    标签: json xml swift3 writetofile


    【解决方案1】:

    猫的类型是NSDictionary,如果你想将JSON保存在文件中,然后使用数据保存。 Swift 也可以使用 Swift 的原生 Dictionary 和 Array 而不是 NSDictionaryNSArray

    manager.post("http://appsandgamesinc.com/api/AppAsUser/getMedias/", parameters: parameters, progress: nil, success: { (task: URLSessionTask, responseObject) in
        if let response = responseObject as? [String:Any],
            let medias = response["medias"] as? [String:Any] {
    
            if let data = try? JSONSerialization.data(withJSONObject: medias) {
                try? data.write(to: URL(fileURLWithPath: file), options: .atomic)
            }
            print("cats:\(cats)")
            NSKeyedArchiver.archivedData(withRootObject: medias)                      
            print("file://"+file)
        }
    })
    

    【讨论】:

    • 感谢您的回复,它有效,但我仍然有一个问题:应该看起来像这样:dg7csqkdaad2n.cloudfront.net/Media/… 出来是这样的:http:\/\/dg7csqkdaad2n.cloudfront.net \/Media\/2262089580297_1494328417.jpeg,我没有解析文件的内容,所以我无法以编程方式修复它有什么想法吗?再次感谢
    • @user3411226 不要遇到你的问题
    • 文件中的网址如下所示:http:\/\/dg7csqkdaad2n.cloudfront.net\/Media\/2262089580297_‌​1494328417.jpeg 会出现错误且无法访问
    • @user3411226 该文件包含这样的 url 或者因为以编程方式存储 JSON?
    • 写入文件后以编程方式存储
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2015-06-26
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多