Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize JSON to string without escape characters in .NET Core?

Tags:

json

c#

.net-core

I would like to serialize a C# object to JSON in a string from .NET Core.

I have tried with this code, but it results in a string with escape characters for the quotes:

string s = JsonConvert.SerializeObject(sensorData);

This is the resulting string:

"{\"Id\":\"100201\",\"Timestamp\":\"2018-02-08T08:43:51.7189855Z\",\"Value\":12.3}"

How can I serialize the object into a string without the escape characters like this?

"{"Id":"100201","Timestamp":"2018-02-08T08:43:51.7189855Z","Value":12.3}"
like image 817
OlavT Avatar asked Feb 08 '18 10:02

OlavT


1 Answers

The escape characters aren't there. If we can reasonably assume that your sensorData is something like:

class SensorData
{
    public int Id { get; set; }
    public DateTime TimeStamp { get; set; }
    public double Value { get; set; }
}

then if I do:

var sensorData = new SensorData {
    Id = 100201,
    TimeStamp = DateTime.Now,
    Value = 12.3,
};
string s = JsonConvert.SerializeObject(sensorData);
Console.WriteLine(s);

the output is:

{"Id":100201,"TimeStamp":"2018-02-08T10:30:40.2290218+00:00","Value":12.3}

The escape characters are an IDE feature, not part of the JSON. The IDE shows you strings as you would need to copy and paste them in your target language; so: if the value is the JSON posted above, then the IDE will show it as a C# literal:

"{\"Id\":100201, ...snip... , \"Value\":12.3}"

But: that isn't the contents of the string.

like image 83
Marc Gravell Avatar answered Nov 14 '22 23:11

Marc Gravell