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

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-08-19 16:35:26 u011212411 阅读数 354

字典转JSON

func convertDictionaryToJSONString(dict:NSDictionary?)->String {
	let data = try? JSONSerialization.data(withJSONObject: dict!, options: JSONSerialization.WritingOptions.init(rawValue: 0))
	let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
	return jsonStr! as String
}

JSON转字典

func convertJSONStringToDictionary(text: String) -> [String:AnyObject]? {
	if let data = text.data(using: String.Encoding.utf8) {
		do {
			return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
		} catch let error as NSError {
			 print(error)
		}
	}
	return nil
}
2017-08-17 18:49:54 a736220388 阅读数 445

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)
2018-02-26 17:59:00 weixin_33754065 阅读数 158
func nsdataToJSON(data: NSData) -> AnyObject? {
    do {
        return try JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) as AnyObject
    } catch {
        print(error)
    }
    return nil
}
2016-10-08 10:22:34 scx_yatoy 阅读数 9673

1、本地json数据如下:data.json

{

"total":2,

"status":"ok",

"data":[

{

"id":1,

"name":"周杰伦",

"head_image":null,

"tel":"1323232232",

"email":"zhoujielun@hotmail.com",

"birth_day":"1990-02-02",

"address":"中国香港"

},

{

"id":2,

"name":"庄心妍",

"head_image":null,

"tel":"1343432345",

"email":"zhuangxinyan@126.com",

"birth_day":"1986-05-22",

"address":"中国河南省"

}

}

2、模型数据 UserData 如下:

class UserData: NSObject,NSCoding {


    var name:String?

    var tel:String?

    var headImgUrlStr:String?

    var email:String?

    var address:String?

}


3、读取本地数据代码如下:

    var userList:NSMutableArray?

    let path =Bundle.main.path(forResource:"data", ofType: "json")

    let url =URL(fileURLWithPath: path!)

    do{

        let data =tryData(contentsOf: url)

        let json:Any =tryJSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers)

        let jsonDic = jsonas!Dictionary<String,Any>

        let datalist = jsonDic["data"]as!NSArray

        userList = UserData.mj_objectArray(withKeyValuesArray: datalist)//该方法在第三个JSON解析库MJExtension中。你可以忽略本行代码

print(datalist)//输出数据

        

    }catchlet erroasError!{

        print("读取本地数据出现错误!",erro)

    }


swift json转字符串

阅读数 25

没有更多推荐了,返回首页