beachCode
beachCode

Reputation: 3510

Swift: escape characters appear in json string

I'm constructing a JSON string by concatenating strings. To get the quotes correct for the web service (no quotes around numbers), I'm using escape characters. When I print the resulting string in Xcode, it looks fine.

{"number":999,"name":"new"}

But when I use Wireshark to capture what's going over the wire, I can see the escape characters in the string.

"{\"number\":999,\"name\":\"new\"}"

Here's the code that creates the string:

let jsonString:String = "{\"number\":" + num + ",\"name\":\"" + name + "\"}"

How can I create the string so the escape characters aren't there? Thanks

Upvotes: 1

Views: 2121

Answers (2)

beachCode
beachCode

Reputation: 3510

The reason I couldn't send the JSON as a dictionary is that Swift dictionaries are unordered. In this case, the server is using MongoDB. I fixed the issue server side instead of trying to hack around it in the client.

Here's the reason: "Why does it happen: MongoDB uses a binary data format called BSON. In BSON, the order of keys always matters. Notice, in JSON an object is an unordered set of key/value pairs." http://devblog.me/wtf-mongo

Upvotes: 1

ellman121
ellman121

Reputation: 1835

I'm fairly certain that the escape characters are being inserted by Wireshark in it's own output.

Upvotes: 0

Related Questions