简体   繁体   中英

IOS JSON escaping special characters

I'm working in IOS and trying to pass some content to a web server via an NSURLRequest. On the server I have a PHP script setup to accept the request string and convert it into an JSON object using the Zend_JSON framework. The issue I am having is whenever the character "ø" is in any part of the request parameters, then the request string is cut short by one character.

Request string before going to server.

[{"description":"Blah blah","type":"Russebuss","name":"Roscoe Simulator","appVersion":"1.0.20","osVersion":"IOS 5.1","phone":"5555555","country":"Østfold","udid":"bed164974ea0d436a43f3cdee0e005a1"}]

Request string on server before any parsing

[{"description":"Blah blah","type":"Russebuss","name":"Roscoe Simulator","appVersion":"1.0.20","osVersion":"IOS 5.1","phone":"5555555","country":"Nord-Trøndelag","udid":"bed164974ea0d436a43f3cdee0e005a1"}

Everything looks exactly the same except the final closing ] is missing. I'm thinking it's having an issue when converting the string to UTF-8, but not sure the correct way to fix this issue.

Does anyone have any ideas why this is happening?

first of all do not trust the xcode console in such cases. you never know which coding the console is actually using.

second, escape the invalid characters before you build you json string. easiest way would probably to make sure you are using the same unicode representation, like utf-8, all the time.

third, if there are still invalid characters use a json lib with a parser (does the encoding). validate the output by parsing back to eg NSString. or validate the output manually by using a web form like http://jsonformatter.curiousconcept.com/

the badest way is to replace the single characters in the string, build your json and convert back. one way to do this could be to replace eg an german ä with its unicode representaion U+00E4 (http://www.utf8-chartable.de/).

Thats the way I do it. I am glad that I nerver needed to go further than step three and this is the step you should do anyway to keep your code simple.

Please try to use Zends internal json Encoding:

Zend_Json::$useBuiltinEncoderDecoder = true;

should fix your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM