Is there a reason you're not just emitting to say, a
StringBuilder
?
I usually just spit out JSON that way. It's so simple it's hard to get it wrong.
The biggest thing is spitting out json string escapes but that's pretty trivial
This will give you a properly escaped JSON string literal from a C# string.
Every other JSON datatype except "null" can be written out with
ToString()
public static string ToStringLiteral(string str)
{
if (null == str) return "null";
StringBuilder result = new StringBuilder();
result.Append("\"");
foreach (char ch in str)
{
switch (ch)
{
case '\b':
result.Append("\\b");
break;
case '\\':
result.Append("\\\\");
break;
case '\t':
result.Append("\\t");
break;
case '\r':
result.Append("\\r");
break;
case '\n':
result.Append("\\n");
break;
case '\"':
result.Append("\\\"");
break;
default:
if (char.IsControl(ch))
{
result.Append("\\u");
ushort u = ch;
result.Append(((byte)(u / 256)).ToString("x2"));
result.Append(((byte)(u % 256)).ToString("x2"));
}
else
result.Append(ch);
break;
}
}
result.Append('\"');
return result.ToString();
}