0

I'm returning objects as JSON results from my APIController inside an ASP.NET MVC web-API.

To convert objects to JSON results I use the below syntax:

return Ok(new WebServiceResult(...));
  1. Are there any methods to convert strings automatically to BASE64 encoding during object to JSON conversions?

  2. Can OK handle non-English characters during JSON conversions and avoid failure to decode that string on other platforms (I mean does it support encodings like UTF-8 or does it handle escape characters that reside inside the contents which are going to be converted such as { character or : character)?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
VSB
  • 9,825
  • 16
  • 72
  • 145
  • 1
    Why do you want to convert *strings* into base64? Base64 is designed to encode *binary* data as text. JSON can represent all Unicode text with no problems. – Jon Skeet Jun 06 '22 at 12:55
  • 1
    Why don't you just try it and see? It wouldn't be much of a JSON serializer if it couldn't serialize strings with double quotes, brackets, etc. – Kirk Woll Jun 06 '22 at 12:55
  • As explained in its [Serialization Guide](https://www.newtonsoft.com/json/help/html/serializationguide.htm#PrimitiveTypes), Json.NET (and also System.Text.Json) will automatically encode any `byte []` property as a Base64 string. If your string represents binary data you could just leave it as `byte []` and let Json.NET encode it as Base64 for you. – dbc Jun 07 '22 at 15:28
  • But if you really have a string you must encode as Base64 for some reason, you will have to apply a custom converter. See [Convert string property value to base64 on serialization](https://stackoverflow.com/a/46040273/3744182), which looks to be a duplicate. – dbc Jun 07 '22 at 15:28
  • 1
    Also, if your JSON contains non-ASCII characters that are getting mangled during transmission (due to encoding inconsistencies or bugs or whatever), you can force them to be escaped by setting `JsonSerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii` as shown in [How to serialize special characters with JsonSerializing](https://stackoverflow.com/a/60580155/3744182) which might also be a duplicate, depending on your actual problem. – dbc Jun 07 '22 at 15:33

0 Answers0