Emoji characters cannot be encoded to JSON

后端 未结 6 1999
长发绾君心
长发绾君心 2021-01-31 06:29

I have a UITextView which I call messageField. The data within that messageField is POST-ed to server in JSON format. When th

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 06:42

    Update Swift & Objective C

    If you want to send send an emoji item through JSON, first you need to formate DB to UTF-8 AND in IOS you need to encode for NSUTF8StringEncoding. So first make sure your DB formate to UTF-8 then encode parameters to NSUTF8StringEncoding.So here is a sample request when sending the message.

        let post:NSString = parameters!
        let url:NSURL = NSURL(string: serverURL!)!
        let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)! // Change Here
        let postLength:NSString = String( postData.length )
        let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("*/*", forHTTPHeaderField: "Accept")
        return request
    

    But you don't need to decode to NSUTF8StringEncoding in iOS.Because according to the apple documentation it decode 5 encodings.

    The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.

    https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error:

提交回复
热议问题