2018-05-04 10:06:25 yingBi2014 阅读数 9129
let str:String = "意大利"
//字符串转Data
let data = str.data(using: String.Encoding.utf8)
//Data转字符串
let newStr = String(data: data!, encoding: String.Encoding.utf8)
print("data=" , data!  , "\n" ,  "newStr=" , newStr!)

输出结果

data= 9 bytes 
newStr= 意大利

2016-03-05 15:18:37 qj918 阅读数 7029
1 String 类型转 NSData 类型
       dataUsingEncoding函数: 将字符串类型(String)的数据转换成数据类型(NSData) 的数据。
       在String类中有自带的函数方法:
  publicfuncdataUsingEncoding(encoding:NSStringEncoding, allowLossyConversion:Bool= default) -> NSData?

2 NSData 类型转 String 类型
var str3 =NSString(data: <NSData>, encoding: <UInt>)

下面在Xcode 中新建playground文件进行测试:

var str1 = "l like read"
var data : NSData = str1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!//UTF8编码 字符串转NSData 
var str2 =  NSString(data: data, encoding: NSUTF8StringEncoding//NSData 转 String 
if(str1== str2){
   print("ok")// 这里会打印这句话 
}
结果如下:

2019-07-08 09:16:12 sun6223508 阅读数 292

1 字典转JSON字符串

        var body = [ "date": “dates”,"time": timestring,"repeat" ]
        let  data2 :Data! = try? JSONSerialization.data(withJSONObject: body, options: [])
        var  JSONString = String(data: data2, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
       

2 字典转Data

 

        var body = [ "date": dates,"time": timestring,"repeat": repeatstring,"remark": remarkstring, "scene_id":cuuentScene["id"]]
        let  data2 :Data! = try? JSONSerialization.data(withJSONObject: body, options: []) 
         

3 Data转JSON字符串

var body = [ "date": “dates”,"time": “timestring”, ]
        let  data2 :Data! = try? JSONSerialization.data(withJSONObject: body, options: [])
        var  JSONString = String(data: data2, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        

4 JSON字符串转Data

var body = [ "date": dates,"time": timestring,"repeat": repeatstring,"remark": remarkstring, "scene_id":cuuentScene["id"]]
  let  data2 :Data! = try? JSONSerialization.data(withJSONObject: body, options: [])
 var  JSONString = String(data: data2, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
 var json=JSONString!.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

 

2019-12-06 11:44:11 happyshaotang2 阅读数 7

#pragma mark - JSON(对象)----->JSON字符串

// 1. 原始方法

//JSON--->data--->JSON字符串
let data = try? JSONSerialization.data(withJSONObject: json, options: [])  
let jsonString = String(data: data, encoding: String.Encoding.utf8)

#pragma mark - JSON字符串----->JSON(对象)

// 1、原生方法

//JSON字符串-->data-->JSON对象
let jsonString = "{\"name\":\"zhangsan\",\"age\": 18}"
let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false) ?? Data()
guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) else {
     return
}


// 2、三方框架(SwiftyJSON: https://github.com/SwiftyJSON/SwiftyJSON)


//JSON字符串-->data-->JSON对象(测试发现直接使用JSON(jsonString).arrayValue是转化不出来的)
let data = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false) ?? Data()
let json = JSON(data).arrayValue

#pragma mark - JSON(对象)----->Data

// 1.原生方法

let data = try? JSONSerialization.data(withJSONObject: json, options: []) 

#pragma mark - Data----->JSON(对象)

// 1、原生方法
guard let array = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String: AnyObject]] else {//转化失败就返回
     return
}

//2、三方框架(SwiftyJSON: https://github.com/SwiftyJSON/SwiftyJSON)
guard let array = JSON(data!).arrayObject as? [[String: AnyObject]] else {//转化失败就返回
    return
}

#pragma mark - JSON字符串----->Data

// 1、原生方法
// string字符串按照String.Encoding.utf8这种编码格式转化为data
if let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false) {
    //.........
}

#pragma mark - Data----->JSON字符串

// 1、原生方法
//只要符合String.Encoding.utf8这种编码的data都能转化成功
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)


// 2. 三方框架(SwiftyJSON: https://github.com/SwiftyJSON/SwiftyJSON)

//如果转化后的字符串不是JSON类型的字符串,则输出null(注意: 该字符串的控制台输出的格式为JSON格式输出,实际类型是字符串!!!)
//本质是先转化为JSON对象再转化为dessription!!!

let jsonString = JSON(jsonData).description

 

2017-08-17 18:49:54 a736220388 阅读数 450

swift (runtime)自定义类转化成字典,Data,JSON字符串

实现部分
class ObjectPrint: NSObject {
    class func getJSON(obj:AnyObject,options:JSONSerialization.WritingOptions)->Data{
        var data = Data()
        do{
            data = try JSONSerialization.data(withJSONObject: self.getObjectDictionary(obj: obj), options: options)
        }
        catch{

        }
        return data
    }
    class func getObjectDictionary(obj:AnyObject)->NSMutableDictionary{
        let dic = NSMutableDictionary()
        var propsCount:UInt32 = 0
        let props = class_copyPropertyList(obj.classForCoder, &propsCount)
        for i in 0..<propsCount {
            let prop = props?[Int(i)]
            let propName = String.init(utf8String: property_getName(prop))

            var value = obj.value(forKey: propName!)
            if value == nil {
                value = NSNull()
            }else{
                value = self.getObjectInternal(obj: value as AnyObject)
            }
            dic.setValue(value, forKey: propName!)
        }
        return dic
    }

    class func getObjectInternal(obj:AnyObject)->AnyObject{
        if obj.isKind(of: NSString.self) || obj.isKind(of: NSNumber.self) || obj.isKind(of: NSNull.self){
            return obj
        }
        if obj.isKind(of: NSArray.self) {
            let arr = NSArray.init(array: obj as! [Any])
            let objArr = NSMutableArray.init(capacity: arr.count)
            for i in 0..<arr.count {
                objArr[i] = self.getObjectInternal(obj: arr[i] as AnyObject)
            }
            return objArr
        }
        if obj.isKind(of: NSDictionary.self) {
            let dic = NSMutableDictionary.init(capacity: (obj as! NSDictionary).count)
            for key in (obj as! NSDictionary).allKeys {
                dic.setObject(self.getObjectInternal(obj: (obj as! NSDictionary).value(forKey: key as! String) as AnyObject), forKey: key as! NSString)
            }
            return dic
        }
        return self.getObjectDictionary(obj:obj)
    }
}
自定义类
class Person: NSObject {
    var name:String?
    var age:NSNumber?
    var children:NSArray?
    var book:NSDictionary?
}
class Child: NSObject {
    var name:NSString?
    var age:NSNumber?
}

调用
let person = Person()
        person.name = "张三"
        person.age = 40
        person.book = ["first":"we","second":"are"]
        let childOne = Child()
        childOne.name = "ddf"
        childOne.age = 2
        let childTwo = Child()
        childTwo.name = "dfgd"
        childTwo.age = 4
        person.children = NSArray(arrayLiteral: childOne,childTwo)
        //自定义类转化成Data或json字符串
        let jsonData = ObjectPrint.getJSON(obj: person, options: JSONSerialization.WritingOptions.prettyPrinted)
        let jsonText = NSString.init(data: jsonData, encoding: String.Encoding.utf8.rawValue)
        print(jsonText!)
        //自定义类转化成字典
        let dic = ObjectPrint.getObjectDictionary(obj: person)
        print(dic)

swift json转字符串

阅读数 43

具体参考文章:开源框架 RSA_Swift

博文 来自: qq_15385613
没有更多推荐了,返回首页