Home > Software engineering >  How does a bullet point become \u2022 in c# for JSON?
How does a bullet point become \u2022 in c# for JSON?

Time:01-19

This isn't a duplicate of JSON and escaping characters - That doesn't answer this, because those code samples are in javascript - I need C#.

What C# method/library converts a bullet point () into \u2022? The same converter would convert a newline char into \n. Those are just 2 examples, but the overall solution I'm looking for is to pass in a string (containing a combination of ASCII and special chars), and it converts all that to the same ASCII, but with the special chars escaped. For example, I need the following string:

• 3 Ply 330 3/16in x 1/16in(#77)
• 25 ft Long X 22 in Wide
• 2022 (2) Beltwall Blk Standard 4in (102mm)

...converted to this:

\u2022 3 Ply 330 3/16in x 1/16in(#77)\n\u2022 25 ft Long X 22 in Wide\n\u2022 (2) Beltwall Blk Standard 4in (102mm)

...so it can become a valid JSON string value.

I have been down a dozen rabbit holes trying to find the answer to this, though I have no doubt it's something ridiculously simple.

CodePudding user response:

You need to set which characters are escaped. If you are using Newtonsoft (comments indicate you are) then by default it will only escape control characters (newlines, etc).

You can pass the option StringEscapeHandling.EscapeNonAscii to have it escape all possible characters.

 public string EncodeNonAsciiCharacters(string value) {
     return JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None,
        new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }
     );
  }
  • Related