如何在 .NET Core 中将 JSON 序列化为没有转义字符的字符串? [英] How to serialize JSON to string without escape characters in .NET Core?

查看:36
本文介绍了如何在 .NET Core 中将 JSON 序列化为没有转义字符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 C# 对象序列化为 .NET Core 字符串中的 JSON.

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);

这是结果字符串:

"{\"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}"

推荐答案

转义字符不存在.如果我们可以合理地假设您的 sensorData 类似于:

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; }
}

如果我这样做:

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

输出为:

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

转义字符是 IDE 功能,不是 JSON 的一部分.IDE 向您显示字符串,因为您需要将它们复制并粘贴到目标语言中;所以:如果值是上面发布的 JSON,那么 IDE 会将它显示作为 C# 文字:

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.

这篇关于如何在 .NET Core 中将 JSON 序列化为没有转义字符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆