问题描述
调用Newtonsoft.Json.JsonConvert.SerializeObject(myObject)
时,我得到的键和值都用双引号引起来,如下所示:
When calling Newtonsoft.Json.JsonConvert.SerializeObject(myObject)
I'm getting keys and values enclosed in double quotes like this:
{"key" : "value"}
我希望将它们括在单引号中,如下所示:
I would like them to be enclosed in single-quotes like this:
{'key' : 'value'}
是否可以使用Json.Net?
Is it possible to do using Json.Net?
推荐答案
是的,这是可能的.如果您显式使用JsonTextWriter
而不是使用JsonConvert.SerializeObject()
,则可以将QuoteChar
设置为单引号.
Yes, this is possible. If you use a JsonTextWriter
explicitly instead of using JsonConvert.SerializeObject()
, you can set the QuoteChar
to a single quote.
var obj = new { key = "value" };
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
using (JsonTextWriter writer = new JsonTextWriter(sw))
{
writer.QuoteChar = '\'';
JsonSerializer ser = new JsonSerializer();
ser.Serialize(writer, obj);
}
Console.WriteLine(sb.ToString());
输出:
{'key':'value'}
提琴: https://dotnetfiddle.net/LGRl1k
请记住,在JSON中的键和值周围使用单引号被认为是非标准的(请参见 JSON.org ),并且可能会导致严格遵守该标准的解析器出现问题.
Keep in mind that using single quotes around keys and values in JSON is considered non-standard (see JSON.org), and may cause problems for parsers that adhere strictly to the standard.
这篇关于告诉Json.Net在序列化对象时写单引号而不是双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!