JSON escape non-ascii characters

Hi,


I´m using Newtonsoft JSON on my c# application and it has the option to escape non-ascii characters when serializing an object.


Here are some simple examples: (using the Newtonsoft JSON library in c#)

string obj = "abcn\n\rüö&/<>"; 
Console.WriteLine(Serialize(obj, StringEscapeHandling.Default)); 
Console.WriteLine(Serialize(obj, StringEscapeHandling.EscapeHtml)); 
Console.WriteLine(Serialize(obj, StringEscapeHandling.EscapeNonAscii));


I'm having a hard time finding any similar functionality using Swift.


This is an example I´m testing with:

        var jsonText = ""
        let dictionary = ["firstName": "Björn", "lastName": "Tärnäby"] as [String : Any]
        if let theJSONData = try? JSONSerialization.data(
            withJSONObject: dictionary,
            options: []) {
            jsonText = String(data: theJSONData, encoding: .utf8)!
            print(jsonText)
        }

It prints out:

{"lastName":"Tärnäby","firstName":"Björn"}


What I would like to achieve is:

{"lastName":"T\u00e4rn\u00e4by","firstName":"Bj\u00f6rn"}


Is there an option in JSONSerialization or some other way to escape my strings in this way?

Answered by QuinceyMorris in 264811022

According to the documentation, it only creates UTF-8 data. So that's a no.


If you convert the data back to a string (as you do in line 6), then it's a String (or perhaps NSString) API question, and I don't know offhand if there is an existing API for this. Perhaps in C stdlib?

Accepted Answer

According to the documentation, it only creates UTF-8 data. So that's a no.


If you convert the data back to a string (as you do in line 6), then it's a String (or perhaps NSString) API question, and I don't know offhand if there is an existing API for this. Perhaps in C stdlib?

Hi, thanks for the quick reply.


I will investigate this a bit more myself. If I run into a solution, I´ll post it here.


There was a need for this kind of functionality, because it was solved in Newtonsoft JSON.


Maybe there is some extension or library that can solve this.


Anyway, thanks for the help.

JSON escape non-ascii characters
 
 
Q