如何在swift中删除json字符串中的额外{brace

时间:2016-03-10 09:39:21

标签: ios arrays json swift

任何人都可以建议我在发送请求之前删除“{'{\ n”。我的api不接受我的参数是值的鳕鱼是发布像{'{\ n key:values}:“”}

这里是我的示例代码:

    let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    self.profieImage = UIImage(named: "calendar.png")

    let imageData = UIImageJPEGRepresentation(self.profieImage, 1)

    let params = ["fname":"Martin","lname":"Raj","gender":"Male","dob":"1997-9-14","email":"xx@gmail.com","mobileNumber":"00000","pancard":"vvvv","profileImg":imageData!] as Dictionary!

    let jsonData = try! NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)

    let theJSONText = NSString(data: jsonData,encoding: NSASCIIStringEncoding)
    print("JSON string = \(theJSONText!)")


    let urlString = NSString(format:"http://my.api.call");
    print("url string is \(urlString)")
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 30
    request.addValue("mobile", forHTTPHeaderField: "true")
    request.addValue("token", forHTTPHeaderField: "")
    request.HTTPBody = theJSONText!.dataUsingEncoding(NSUTF8StringEncoding)



    let dataTask = session.dataTaskWithRequest(request)
        {
            (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
            // 1: Check HTTP Response for successful GET request
            guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
                else {
                    print("error: not a valid http response")
                    return
            }

            switch (httpResponse.statusCode){
            case 200:
                let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)

                print("response==\(response)")

                default:
                break
            }    
    }

我的BackEnd日志打印此语句:

 { '{\n  "dob" : "1997",\n  "validatedId" : "sdfdfdf",\n  "pancard" : "rrrrr",\n  "email" : "xx@gmail.com",\n  "sameGender" : "1",\n  "profileImg" : "mobileNumber" : "1230123012",\n  "fname" : "Martin"\n}': '' }

但我必须发送像这样的值

{
"dob" : "1997",
"validatedId" : "dfdsfdsf",
"pancard" : "vvvvv",
"email" : "xx@gmail.com",
"sameGender" : "1"
 }

1 个答案:

答案 0 :(得分:0)

在这个地方

 let params = ["fname":"Martin","lname":"Raj","gender":"Male","dob":"1997-9-14","email":"xx@gmail.com","mobileNumber":"00000","pancard":"vvvv","profileImg":imageData!] as Dictionary!

不需要这个

 let jsonData = try! NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)

let theJSONText = NSString(data: jsonData,encoding: NSASCIIStringEncoding)
print("JSON string = \(theJSONText!)")
  

原因你已经创建了dictioanry并再次转换为新的JSOn字符串,这样你得到组合字典的原因,使用单个字典就足够了或使用String并将你的字符串转换为JSon字符串

直接使用

 let params = ["fname":"Martin","lname":"Raj","gender":"Male","dob":"1997-9-14","email":"xx@gmail.com","mobileNumber":"00000","pancard":"vvvv","profileImg":imageData!] as Dictionary!
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)