0

I'm using the new Json Serializer included in .Net Core (not Newtonsoft).

I am enconding a phone number in an object with the country code, so I have an object with a string property which holds the number. Example:

public class MyObject {
    public string phoneNumber { get; set; }
}

var myObject = new MyObject() {
    phoneNumber = "+569123123123"
}

I need to encode this object as a Json, so I do:

var jsonToSend = System.Text.Json.JsonSerializer.Serialize(myObject);

What I get as a result is this:

 {
    "phoneNumber":"\u002B569123123123"
 }

What I need is this:

{
  "phoneNumber":"+569123123123"
}

So, I need to find a way to disable the encoding of special characters

BTW I'm assuming this is the Json generated because I'm using the Text Visualizer of Visual Studio to inspect the variable in debugging.

Thanks in advance.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Cristopher Rosales
  • 476
  • 1
  • 4
  • 14
  • That's not even a special character – Panagiotis Kanavos Feb 07 '20 at 14:47
  • 1
    Note that if your JSON parser stumbles over this, you've got a bad JSON parser. It is legal to escape any character in a JSON string, even for characters where it's not strictly required (and `+` is special in many contexts where strings are passed online, most prominently URIs, so escaping it pre-emptively is by no means a bad idea). – Jeroen Mostert Feb 07 '20 at 14:51
  • The docs for the [UnsafeRelaxedJsonEscaping](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder.unsaferelaxedjsonescaping?view=netcore-3.1) explain that those characters are encoded by default to make the string safe for use in HTML. Other Json serializers dont' have any problem handling the escape sequences. From the [JSON RFC](https://www.ietf.org/rfc/rfc4627.txt) `Any character may be escaped.`. If some parser chokes on this, it has a serious bug – Panagiotis Kanavos Feb 07 '20 at 14:54

0 Answers0