any转data swift

2019-06-19 17:22:58 sun6223508 阅读数 1281

var mBytes:[UInt8]  =  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

var data:Data = Data(bytes: mBytes, count: mBytes.count);

 

 

 

 

var bytes = [UInt8](data)

print(bytes)

2019-01-28 17:20:43 qq_37191821 阅读数 732

/** array 转 jsonString */

    private func stringFromArray(_ array:Array<Any>?)->String{

        if array != nil {

            if JSONSerialization.isValidJSONObject(array!) == false {

                return "无法解析出";

            }

            do{

                let data = try JSONSerialization.data(withJSONObject: array!, options: []);

                let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue);

                if jsonString != nil {

                    return jsonString! as String;

                }

            }catch{}

        }

        return String();

    }

    /** json 转 jsonString */

    private func stringFromDictionary(_ json:Dictionary<String, Any>?)->String{

        if json != nil {

            if JSONSerialization.isValidJSONObject(json!) == false{

                return "无法解析出";

            }

            do{

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

                let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue);

                if(jsonString != nil){

                    return jsonString! as String;

                }

            }catch{}

        }

        return String();

    }

    /** string 转 json*/

    private func dictionaryFromString(_ string:String?)->Dictionary<String, Any>{

        if string != nil {

            let data = string?.data(using: .utf8);

            do{

                let json = try JSONSerialization.jsonObject(with: data ?? Data(), options: .mutableContainers)

                return json as! Dictionary<String, Any> ;

            }catch{}

        }

        return Dictionary();

    }

    /** string 转 array*/

    private func arrayFromString(_ string:String?)->Array<Any>{

        if string != nil {

            let data = string?.data(using: .utf8);

            do{

                let jsonArray = try JSONSerialization.jsonObject(with: data ?? Data(), options: .mutableContainers)

                return jsonArray as! Array<Any>;

            }catch{}

        }

        return Array();

    }

2017-07-12 17:20:45 xuzenghuifeng 阅读数 1693

AnyObject

官方api中AnyObject的介绍分为三方面内容,看完相信你会有所收获

The protocol to which all classes implicitly conform. //隐含类型确认协议

You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.
当你需要灵活的类型或者当你调用返回未知类型结果的oc方法和属性时,你需要使用AnyObject。
AnyObject可以作为任何类,类的类型(type),或者是类协议的有型的类型来使用。
For example:
//例如

     class FloatRef {
         let value: Float
         init(_ value: Float) {
             self.value = value
         }
     }
     let x = FloatRef(2.3)
     let y: AnyObject = x
     let z: AnyObject = FloatRef.self

AnyObject can also be used as the concrete type for an instance of a type that bridges to an Objective-C class.
Many value types in Swift bridge to Objective-C counterparts, like String and Int.
AnyObject也可以被用作为一个oc对象的有型的类型。swift中的许多值类型和oc里面的是相通的,比如StringInt

 let s: AnyObject = "This is a bridged string." as NSString
     print(s is NSString)
     // Prints "true"

     let v: AnyObject = 100 as NSNumber
     print(type(of: v))
     // Prints "__NSCFNumber"

The flexible behavior of the AnyObject protocol is similar to
Objective-C’s id type. For this reason, imported Objective-C types
frequently use AnyObject as the type for properties, method parameters,
and return values.
AnyObject协议的灵活性与oc中的id是类似的。由于这个原因,AnyObject被频繁地作为oc类的属性、方法参数的类型来使用

Casting AnyObject Instances to a Known Type //抛出AnyObject对象给一个已知类型

Objects with a concrete type of AnyObject maintain a specific dynamic type and can be cast to that type using one of the type-cast operators
(as, as?, or as!).
This example uses the conditional downcast operator (as?) to conditionally cast the s constant declared above to an instance of Swift’s String type.
固定的类型的AnyObject对象具有一个具体的动态类型,并且可以使用(as, as?, or as!)被抛向那个具体的类型。下面的例子使用(as?)抛向上面声明的Swift中String 类型的对象s

     if let message = s as? String {
         print("Successful cast to String: \(message)")
     }
     // Prints "Successful cast to String: This is a bridged string."

If you have prior knowledge that an AnyObject instance has a particular
type, you can use the unconditional downcast operator (as!). Performing
an invalid cast triggers a runtime error.
如果你事先知道AnyObject 对象的详细类型,可以使用 (as!)。执行无效的抛向操作会引起运行时错误。

  let message = s as! String
     print("Successful cast to String: \(message)")
     // Prints "Successful cast to String: This is a bridged string."

     let badCase = v as! String
     // Runtime error

Casting is always safe in the context of a switch statement.
但在switch 语句中抛向操作是不会引起运行时错误的。

    let mixedArray: [AnyObject] = [s, v]
     for object in mixedArray {
         switch object {
         case let x as String:
             print("'\(x)' is a String")
         default:
             print("'\(object)' is not a String")
         }
     }
     // Prints "'This is a bridged string.' is a String"
     // Prints "'100' is not a String"

Accessing Objective-C Methods and Properties //访问OC方法和属性

When you use AnyObject as a concrete type, you have at your disposal every @objc method and property—that is, methods and properties imported from Objective-C or marked with the @objc attribute. Because Swift can’t guarantee at compile time that these methods and properties are actually available on an AnyObject instance’s underlying type, these @objc symbols are available as implicitly unwrapped optional methods and properties, respectively.

当你使用 AnyObject 作为一个有型的类型,你必须处理每一个带 @objc 标记或者来自于oc的方法和属性。因为Swift不能保证 潜在类型的AnyObject对象的这些方法和属性是真正可用,带有@objc 标记的方法和属性会分别在暗中被解绑。

This example defines an IntegerRef type with an @objc method named
getIntegerValue().
这个例子定义了一个IntegerRef ,它有一个标记了@objc 方法 getIntegerValue()

     class IntegerRef {
         let value: Int
         init(_ value: Int) {
             self.value = value
         }

         @objc func getIntegerValue() -> Int {
             return value
         }
     }

     func getObject() -> AnyObject {
         return IntegerRef(100)
     }

    let obj: AnyObject = getObject()

In the example, obj has a static type of AnyObject and a dynamic type of IntegerRef. You can use optional chaining to call the @objc method getIntegerValue() on obj safely. If you’re sure of the dynamic type of obj, you can call getIntegerValue() directly.
这个例子中 ocj有一个AnyObject静态类型和一个IntegerRef动态类型。 你可以使用可选链通过 obj调用带有 @objc标记的方法getIntegerValue()。如果你确定obj的动态类型,你可以直接调用。

  let possibleValue = obj.getIntegerValue?()
     print(possibleValue)
     // Prints "Optional(100)"

     let certainValue = obj.getIntegerValue()
     print(certainValue)
     // Prints "100"

If the dynamic type of obj doesn’t implement a getIntegerValue()
method, the system returns a runtime error when you initialize
certainValue.
Alternatively, if you need to test whether obj.getIntegerValue() exists, use optional binding before calling the method.
如果动态类型obj没有getIntegerValue()方法,当你初始化certainValue的时候,系统会出现运行时错误。除非,你调用这个方法之前,先使用可选的绑定检验下obj.getIntegerValue()是否存在

  if let f = obj.getIntegerValue {
         print("The value of 'obj' is \(f())")
     } else {
         print("'obj' does not have a 'getIntegerValue()' method")
     }
     // Prints "The value of 'obj' is 100"
2018-08-28 02:15:38 weixin_33913377 阅读数 325

这是Dictionary转Data 的方法

源码:

func jsonToData(jsonDic:Dictionary<String, Any>) -> Data? {

    if (!JSONSerialization.isValidJSONObject(jsonDic)) {

        print("is not a valid json object")

        return nil

}

    //利用自带的json库转换成Data

    //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读

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

    //Data转换成String打印输出

    let str = String(data:data!, encoding: String.Encoding.utf8)

    //输出json字符串

    print("Json Str:\(str!)")

    return data

}

复制代码

这是Data转Dictionary, 上面是首先判断能否转换成功,下面用的do catch。

源码:

func dataToDictionary(data:Data) ->Dictionary<String, Any>?{

    do{

        let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

        let dic = json as! Dictionary<String, Any>

        return dic

    }catch _ {

        print("失败")

        return nil

    }

}
复制代码

首先因为是自己写的Demo,所以先定义Dictionary,转为Data,然后再转成Dictionary。 定义好你需要的变量,也就是成员,然后将解析出来的Dictionary的key定义为一个数组(例子中就是我定义的Dictionary的key,实际项目中就是你得到的返回值对应的key),再将你与之相对应的变量定义为一个数组,顺序要对应上。然后遍历数组并赋值

Model源码:

class testModel:NSObject{

    var name:String!

    var age:String!

    var sex:String!

    convenience init(dic:Dictionary<String, Any>){

        self.init()    

        let arr1 = ["姓名","年龄","性别"]

        let arr2 = ["name","age","sex"]

        for (index, value) in arr1.enumerated() {

            self.setValue(dic[value], forKey: arr2[index])

        }

    }

}

复制代码

处理这些之后调用就很简单了,传入Dictionary就搞定了所有的赋值。这样子的Model同样适用于第三方库解析出来的数据,例如SwiftJSON,区别只是传入的字典类型改为JSON。

  let dic = dataToDictionary(data:data)
  let model = testModel.init(dic: dic!)
复制代码
2016-12-29 18:54:49 C_calary 阅读数 4459
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 ""
    }
}