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}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With