• Swift JSON字符串和字典以及数组的互转


    1、JSONString转换为字典

        // JSONString转换为字典
     
        func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
    
            let jsonData:Data = jsonString.data(using: .utf8)!
    
            let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            if dict != nil {
                return dict as! NSDictionary
            }
            return NSDictionary()
            
    
        }
    

    2、JSONString转换为数组

    func getArrayFromJSONString(jsonString:String) ->NSArray{
            
            let jsonData:Data = jsonString.data(using: .utf8)!
            
            let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            if array != nil {
                return array as! NSArray
            }
            return array as! NSArray
            
        }
    

      

    3、字典转换为JSONString

    /**
         字典转换为JSONString
         
         - parameter dictionary: 字典参数
         
         - returns: JSONString
         */
        func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
            if (!JSONSerialization.isValidJSONObject(dictionary)) {
                print("无法解析出JSONString")
                return ""
            }
            let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
            let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
            return JSONString! as String
    
        }
    

     

    4、数组转换为JSONString

        //数组转json
        func getJSONStringFromArray(array:NSArray) -> String {
            
            if (!JSONSerialization.isValidJSONObject(array)) {
                print("无法解析出JSONString")
                return ""
            }
            
            let data : NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData!
            let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
            return JSONString! as String
            
        }
    

      

  • 相关阅读:
    用汇编的眼光看c++(之模板函数) 四
    从B树、B+树、B*树谈到R 树 四
    how to locate dll in native c++ world / dotnet world?
    GAC和sidebyside
    ARM VS Intel
    关于dotnet下的encoding
    synchronization objects for interprocess synchronization and multithreadiing
    [remote debug]WinDBG 技巧: 如何用WinDBG远程调试程序
    [tip]transparent bmp
    Review: functor / function object
  • 原文地址:https://www.cnblogs.com/jukaiit/p/9345654.html
Copyright © 2020-2023  润新知