码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-07-21 11:47:52      阅读:361      评论:0      收藏:0      [点我收藏+]

标签:val   getjson   nsdata   数组   string   bsp   无法   odi   obj   

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

    }

  

 

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

标签:val   getjson   nsdata   数组   string   bsp   无法   odi   obj   

原文地址:https://www.cnblogs.com/jukaiit/p/9345654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!