2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#のDataContractJsonSerializerでインデントをして出力する(minifyしない方法)

Posted at

C#でJsonをシリアライズする一つの方法に DataContractJsonSerializerがある。
これを使ってファイルに書き込むためには以下のように記述する。

        public void Save(T data)
        {
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(fs,data);
            }
        }

インデントされずに1行で出力されてしまうのだが設定ファイルだとかに使いたい場合は不便。
何とかできないものかと逆コンパイルして追ってみるとWriteObjectは
JsonReaderWriterFactory.CreateJsonWriterなるものを使っているそう。
WriteObjectはXmlWriterでもオーバーロードされているので、このCreateJsonWriterで作ったWriterを以下のように渡せば、インデントが可能となる。

        public void Save(T data)
        {
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            using (var writer = JsonReaderWriterFactory.CreateJsonWriter(fs, Encoding.UTF8, true, true))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(writer, data);
            }
        }
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?