1. 程式人生 > >Swift3.0 Any資料型別轉Json

Swift3.0 Any資料型別轉Json

func toolsChangeToJson(info: Any) -> String{
    //首先判斷能不能轉換
    guard JSONSerialization.isValidJSONObject(info) else {
        PrintLog("json轉換失敗")
        return ""
    }
    //如果設定options為JSONSerialization.WritingOptions.prettyPrinted,則列印格式更好閱讀
    let jsonData = try? JSONSerialization.data(withJSONObject: info, options: [])

    if
let jsonData = jsonData { let str = String(data: jsonData, encoding: String.Encoding.utf8) return str ?? "" }else { return "" } }