最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[基本解决]swift中将NSData转换为string或JSON或NSDictionary

iOS crifan 1053浏览 0评论

折腾:

[已解决]swift中确认Alamofire中Http的POST参数时编码用ParameterEncoding.JSON是否可以把布尔型变量输出为true和false

期间,现在已有NSData的变量:HTTPBody

    @NSCopying public var HTTPBody: NSData? { get }

response.request?.HTTPBody

需要将其转换为对应的字典或字符串

swift nsdata to json

swift nsdata to string

xcode – Converting JSON to NSData, and NSData to JSON in Swift – Stack Overflow

结果去用代码:

            if let httpBodyData = response.request?.HTTPBody {

                do {

                   let decodedHttpBodyJson = try NSJSONSerialization.JSONObjectWithData(httpBodyData, options: NSJSONReadingOptions.AllowFragments)

                    gLog.info("decodedHttpBodyJson=\(decodedHttpBodyJson)")

                    /*

                    decodedHttpBodyJson={

                        customer =     {

                            comeFrom = 0;

                            datafrom = 2;

                            followup = 4;

                            name = "";

                            phone = "";

                            salesId = 10000010;

                            testdrive = 1;

                            topComeFrom = 0;

                        };

                        intentedcar =     {

                            color = 0;

                            series = 0;

                            spec = 0;

                        };

                    }

                     */

                } catch (let error as NSError) {

                    gLog.error("error=\(error)")

                }

            }

输出的是:Bool的testdrive输出为1,而不是true

然后用SwiftyJSON去解码,却输出unknown

                    let httpBodyJson = JSON(data: httpBodyData)

                    gLog.verbose("httpBodyJson=\(httpBodyJson)")

                    //httpBodyJson=unknown

参考:

How to initialise a string from NSData in Swift – Stack Overflow

去转换为String

然后发现,是正常的:

Boo被转换为true(或false)

并且,刚才异常的JSON转换,现在也正常了:

                   let httpBodyJson = JSON(data: httpBodyData)

                    gLog.verbose("httpBodyJson=\(httpBodyJson)")

                    //httpBodyJson=unknown

                    /*

                    httpBodyJson={

                      "customer" : {

                        "followup" : 4,

                        "datafrom" : 2,

                        "phone" : "",

                        "name" : "",

                        "topComeFrom" : 0,

                        "salesId" : 10000010,

                        "testdrive" : true,

                        "comeFrom" : 0

                      },

                      "intentedcar" : {

                        "color" : "0",

                        "spec" : "0",

                        "series" : "0"

                      }

                    }

                     */

                    let httpBodyJsonStr = NSString(data: httpBodyData, encoding:NSUTF8StringEncoding)

                    gLog.verbose("httpBodyJsonStr=\(httpBodyJsonStr)")

                    //httpBodyJsonStr=Optional({"customer":{"salesId":10000010,"phone":"","followup":4,"testdrive":true,"name":"","datafrom":2,"topComeFrom":0,"comeFrom":0},"intentedcar":{"series":"0","color":"0","spec":"0"}})

全部的测试代码:

           if let httpBodyData = response.request?.HTTPBody {

                do {

                   let decodedHttpBodyDict = try NSJSONSerialization.JSONObjectWithData(httpBodyData, options: NSJSONReadingOptions.AllowFragments)

                    gLog.info("decodedHttpBodyDict=\(decodedHttpBodyDict) type=\(decodedHttpBodyDict.dynamicType)")

                    /*

                    decodedHttpBodyDict={

                        customer =     {

                            comeFrom = 0;

                            datafrom = 2;

                            followup = 4;

                            name = "";

                            phone = "";

                            salesId = 10000010;

                            testdrive = 1;

                            topComeFrom = 0;

                        };

                        intentedcar =     {

                            color = 0;

                            series = 0;

                            spec = 0;

                        };

                    }

                     type=__NSCFDictionary

                     */

                    let httpBodyJson = JSON(data: httpBodyData)

                    gLog.verbose("httpBodyJson=\(httpBodyJson)")

                    //httpBodyJson=unknown

                    /*

                    httpBodyJson={

                      "customer" : {

                        "followup" : 4,

                        "datafrom" : 2,

                        "phone" : "",

                        "name" : "",

                        "topComeFrom" : 0,

                        "salesId" : 10000010,

                        "testdrive" : true,

                        "comeFrom" : 0

                      },

                      "intentedcar" : {

                        "color" : "0",

                        "spec" : "0",

                        "series" : "0"

                      }

                    }

                     */

                    let httpBodyJsonStr = NSString(data: httpBodyData, encoding:NSUTF8StringEncoding)

                    gLog.verbose("httpBodyJsonStr=\(httpBodyJsonStr)")

                    //httpBodyJsonStr=Optional({"customer":{"salesId":10000010,"phone":"","followup":4,"testdrive":true,"name":"","datafrom":2,"topComeFrom":0,"comeFrom":0},"intentedcar":{"series":"0","color":"0","spec":"0"}})

                } catch (let error as NSError) {

                    gLog.error("error=\(error)")

                }

            }

[总结]

NSData转换为String的话,可以:

let jsonStr = NSString(data: someNSData, encoding:NSUTF8StringEncoding)

NSData转换为JSON对象,比如SwiftyJSON的话,可以:

let json = JSON(data: someNSData)

NSData转换为swift语言自带的JSON对象的话,可以用:

                do {

                   let decodedDict = try NSJSONSerialization.JSONObjectWithData(someNSData, options: NSJSONReadingOptions.AllowFragments)

                    print("type=\(decodedDict.dynamicType)")

                    //type=__NSCFDictionary

                } catch (let error as NSError) {

                    print("error=\(error)")

                }

但是需要注意的是此处print出来的Dictionary对象,print出来的内容中,对于Bool值,是1或0(而不是JSON标准中的true或false)

转载请注明:在路上 » [基本解决]swift中将NSData转换为string或JSON或NSDictionary

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
57 queries in 0.264 seconds, using 18.84MB memory