Home > Blockchain >  How to serialize an object with newtonsoft, which has a value with backslash [\]
How to serialize an object with newtonsoft, which has a value with backslash [\]

Time:01-19

I prepared this small example to show you my problem (vb.net and Newtonsoft)

I would prefer that the solution be done with Newtonsoft.

    Public Class Message
        Property Emoji As String
    End Class


    Public Sub GetJson()

        Dim msgObject As New Message With {.Emoji = "\uD83D\uDE00"}

        'Option 1
        Dim JsonSerializerSettings As New JsonSerializerSettings
        JsonSerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
        Dim msgJson_1 As String = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject, JsonSerializerSettings)

        'Option 2
        Dim msgJson_2 As String = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject, Newtonsoft.Json.Formatting.None)

        'Option 3
        Dim stringWriter As New StringWriter()
        Using writer As New JsonTextWriter(stringWriter)
            writer.Formatting = Formatting.None
            Dim serializer As New JsonSerializer()
            serializer.Serialize(writer, msgObject)
        End Using
        Dim msgJson_3 As String = stringWriter.ToString()

    End Sub

with none of the three options works, it always results in

{
    "Emoji": "\\uD83D\\uDE00"
}

The result I need is

{
    "Emoji": "\uD83D\uDE00"
}

How do I set Newtonsoft to not take into account the backslash character, as an escaped character?

Another unorthodox way could be:

jsonString = jsonString.replace("//","/") 

I do not really like

Thanks!!!!

CodePudding user response:

\ is an escape char in JSON hence if you try and serialise a \ it gets escaped as \\ then when you deserialise \\ you get \

My guess is you have been given an example asking you to send "Emoji": "\uD83D\uDE00"

In json (and C#) \u#### specifies a unicode character (usually for something not found on a keyboard) as you are using VB.NET instead you should use $"{ChrW(&HD83D)}{ChrW(&HDE00)}"

CodePudding user response:

"jsonString = jsonString.replace("//","/") " will never work, this is more safe way

json = json.Replace("\\\\u","\\u");

or since you don't like old, good classical solutions

json = Regex.Replace(json, @"\\u", @"u");
//or
json = json.Replace(@"\\u", @"\u"); 

even this will work in your case ( but I will not recommend for another cases since it is not safe)

json = Regex.Unescape(json);
  • Related