在Json.Net中生成换行而不是CRLF

Ric*_*der 9 c# json json.net

对于我的unix/java朋友,我想在Json.Net中发送换行符('\n')而不是CRLF('\ r \n').我尝试将StreamWriter设置为使用换行而没有任何成功.

我认为Json.Net代码正在使用Environment.NewLine而不是调用TextWriter.WriteNewLine().更改Environment.NewLine不是一个选项,因为我作为服务器运行,并且换行编码基于请求.

有没有其他方法来强制换取crlf?

这是我的代码 -

using (var streamWriter = new StreamWriter(writeStream, new UTF8Encoding(false))
{
     NewLine = "\n"
})
using (var jsonWriter = new JsonTextWriter(streamWriter) 
{ 
     CloseOutput = true, 
     Indentation = 2, 
     Formatting = Formatting.Indented 
})
{
       // serialise object to JSON
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*der 8

在深入研究Json.Net代码之后,我看到了问题JsonTextWriter.WriteIndent,感谢Athari.

而不_writer.Write(Environment.NewLine);应该是_writer.WriteLine();.

我已经向github发布了拉取请求.https://github.com/JamesNK/Newtonsoft.Json/pull/271


Ath*_*ari 6

如果要自定义缩进空格,只需覆盖JsonTextWriter.WriteIndent:

public class JsonTextWriterEx : JsonTextWriter
{
    public string NewLine { get; set; }

    public JsonTextWriterEx (TextWriter textWriter) : base(textWriter)
    {
        NewLine = Environment.NewLine;
    }

    protected override void WriteIndent ()
    {
        if (Formatting == Formatting.Indented) {
            WriteWhitespace(NewLine);
            int currentIndentCount = Top * Indentation;
            for (int i = 0; i < currentIndentCount; i++)
                WriteIndentSpace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


mas*_*son 6

我在这里看到了几个配置序列化器的解决方案。但如果你想要快速而肮脏,只需将字符替换为你想要的字符即可。毕竟,JSON 只是一个字符串。

string json = JsonConvert.SerializeObject(myObject);
json = json.Replace("\r\n", "\n");
Run Code Online (Sandbox Code Playgroud)