サンプルコード
indentJson.cs
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Xml;
class Example
{
public static void Main(string[] args)
{
string json = "[{\"color\":\"red\",\"value\":\"#f00\"}," +
"{\"color\":\"green\",\"value\":\"#0f0\"}," +
"{\"color\":\"blue\",\"value\":\"#00f\"}," +
"{\"color\":\"cyan\",\"value\":\"#0ff\"}," +
"{\"color\":\"magenta\",\"value\":\"#f0f\"}," +
"{\"color\":\"yellow\",\"value\":\"#ff0\"}," +
"{\"color\":\"black\",\"value\":\"#000\"}]";
string indented = convertToIndentedJson(json);
System.Console.WriteLine("in:");
System.Console.WriteLine(json);
System.Console.WriteLine();
System.Console.WriteLine("out:");
System.Console.WriteLine(indented);
}
private static string convertToIndentedJson(string json)
{
byte[] buffer = Encoding.UTF8.GetBytes(json);
using (MemoryStream stream = new MemoryStream())
using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, true, true))
using (XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(buffer, XmlDictionaryReaderQuotas.Max))
{
writer.WriteNode(reader, true);
writer.Flush();
return Encoding.UTF8.GetString(stream.ToArray());
}
}
}
コンパイル用のバッチファイル
indentJson.cs.bat
@setlocal
@pushd "%~dp0"
@for %%1 in ("%~n0") do @set "BASENAME=%%~n1"
@for /d %%1 in (%SystemRoot%\Microsoft.NET\Framework\v*) do @if exist "%%~1\csc.exe" set "CSC=%%~1\csc.exe"
@for /d %%1 in (%SystemRoot%\Microsoft.NET\Framework64\v*) do @if exist "%%~1\csc.exe" set "CSC64=%%~1\csc.exe"
"%CSC%" /target:exe /platform:x86 /optimize+ /warnaserror+ /out:"%BASENAME%.exe" "%~n0"
"%CSC64%" /target:exe /platform:x64 /optimize+ /warnaserror+ /out:"%BASENAME%64.exe" "%~n0"
@popd
@endlocal
実行結果
>indentJson.exe
in:
[{"color":"red","value":"#f00"},{"color":"green","value":"#0f0"},{"color":"blue","value":"#00f"},{"color":"cyan","value":"#0ff"},{"color":"magenta","value":"#f0f"},{"color":"yellow","value":"#ff0"},{"color":"black","value":"#000"}]
out:
[
{
"color": "red",
"value": "#f00"
},
{
"color": "green",
"value": "#0f0"
},
{
"color": "blue",
"value": "#00f"
},
{
"color": "cyan",
"value": "#0ff"
},
{
"color": "magenta",
"value": "#f0f"
},
{
"color": "yellow",
"value": "#ff0"
},
{
"color": "black",
"value": "#000"
}
]
ポイント
-
CreateJsonWriter()
の第4引数がindent
なので、こいつへtrue
を指定すること