JD2022-TU1/main/tools/framework/JD.Serialization/Serializers/Json/JsonWriter.cs

136 lines
No EOL
3.3 KiB
C#

using System;
using System.IO;
namespace JD.Serialization
{
/// <summary>
/// Basic utility that helps to output json.
/// </summary>
internal class JsonWriter : IDisposable
{
private readonly TextWriter m_textWriter;
private int m_indentationLevel;
private string m_pendingString = "";
public bool IgnoreDefaultValues = true;
public bool CommentDefaultValues = false;
public int CommentCount;
public JsonWriter(TextWriter writer)
{
m_textWriter = writer;
}
public void Dispose()
{
FlushPending(removeComma:true);
m_textWriter.Dispose();
}
public int IndentationLevel
{
get { return m_indentationLevel; }
set { m_indentationLevel = value; }
}
public void WriteComma()
{
FlushPending(removeComma: false);
m_pendingString = "," + Environment.NewLine;
}
public void WriteLine(string format, params object[] args)
{
FlushPending(removeComma: false);
for (int i = 0; i < m_indentationLevel; ++i)
{
m_textWriter.Write(" ");
}
if (CommentCount > 0)
{
m_textWriter.Write("// ");
}
if (args != null && args.Length > 0)
{
m_pendingString = string.Format(format, args) + Environment.NewLine;
}
else
{
m_pendingString = format + Environment.NewLine;
}
}
public void Write(string text)
{
m_textWriter.Write(text);
}
private void FlushPending(bool removeComma)
{
if (m_pendingString != null)
{
if (removeComma)
{
m_pendingString = m_pendingString.Replace(",", "");
}
m_textWriter.Write(m_pendingString);
m_pendingString = null;
}
}
/// <summary>
/// Starts/ends a block.
/// </summary>
/// <returns></returns>
public IDisposable Indent()
{
WriteLine("{");
IndentationLevel++;
return new DisposableHelper(() =>
{
IndentationLevel--;
FlushPending(removeComma: true);
WriteLine("},");
});
}
/// <summary>
/// Starts/ends an array block.
/// </summary>
/// <returns></returns>
public IDisposable IndentArrayBlock()
{
WriteLine("[");
IndentationLevel++;
return new DisposableHelper(() =>
{
IndentationLevel--;
FlushPending(removeComma: true);
WriteLine("],");
});
}
private class DisposableHelper : IDisposable
{
private readonly System.Action _action;
public DisposableHelper(System.Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
}