swift 服務端要求json對象怎麼辦?(二)

來源:互聯網
上載者:User

標籤:

還記得上次post請求的參數格式嗎?

“{‘name’:dog‘,‘password‘:‘123‘}”

為什麼要這麼寫呢?

一:網路編程,你需要一個利器抓包工具,Fiddler 這個就不錯,我發現抓到的http contentType ="application/x-www-form-urlencoded" 額,好吧,我想要的是contentType=“application/json”,到YYHRequest中看看那裡設定,

 func serializeRequestParameters() {        contentType = "application/x-www-form-urlencoded"                if (method == "GET") {            if let queryURL = queryParametersURL() {                url = queryURL            }        } else {            body = serializedRequestBody()        }    }    
啊,是這裡,立馬改成 contentType=“application/json”,好吧,跑起來看看,還是沒什麼卵用

二:那還是沿著原來的路線來吧

寫個方法吧,乾脆

 func ConvertType(parameters:Dictionary<String,String>)->String{            var para:Dictionary<String,String> = parameters                        var paraStr:String="{"                for (key, value) in para{            paraStr = paraStr + "'" + key + "'" + ":" + "'" + value + "'" + ","        }                let rangeOfPara = Range(start: paraStr.startIndex,            end: advance(paraStr.endIndex, -1))                let finalStr = paraStr.substringWithRange(rangeOfPara)                var parametersStr:String = finalStr + "}"                        return parametersStr    }


這樣的話,你就可以吧字典轉為需要的“{‘name’:dog‘,‘password‘:‘123‘}”類型了


如果有多個,多層,那你就需要不斷的迴圈添加了

 var strTest:[String]=[]  var n:Int=5  for i in 0…n{       let parameter1:Dictionary<String,String> =  [“a”:”1” ]        let parameter2:Dictionary<String,String>  =  [“a”:”1” ]        strTest.insert("{“+self.ConvertType(parameter1)+ self.ConvertType        (parameter2)+"}", atIndex: strTest.endIndex)                     }println(strTest )

這樣最後就生產出來伺服器需要的格式了大致如下

"[{‘a‘:{‘aa‘:‘1‘},‘b‘:[{‘a‘:‘1‘},{}]},{},{},{},{}]"

三:總結:

其實主要的思路就是:先看你要什麼格式,比如我要的就是“{‘name’:dog‘,‘password‘:‘123‘}”這種類型,然後再利用for  key value 的方法來變數字典中的值,給他拼接成你想要的最後格式

swift 服務端要求json對象怎麼辦?(二)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.