C# を使用して .NET でフォーマットされた JSON を取得するにはどうすればよいでしょうか? 質問する

C# を使用して .NET でフォーマットされた JSON を取得するにはどうすればよいでしょうか? 質問する

私は .NET JSON パーサーを使用しており、構成ファイルを読み取り可能なようにシリアル化したいと考えています。そのため、次の代わりに:

{"blah":"v", "blah2":"v2"}

もっと素敵なものがほしいです:

{
    "blah":"v", 
    "blah2":"v2"
}

私のコードは次のようになります:

using System.Web.Script.Serialization; 

var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))
{
    f.WriteLine(configSz);
    f.Close();
}

ベストアンサー1

JavaScriptSerializer でこれを実現するのは困難です。

試すJSON.Net

JSON.Netの例から若干の変更を加えたもの

using System;
using Newtonsoft.Json;

namespace JsonPrettyPrint
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Product product = new Product
                {
                    Name = "Apple",
                    Expiry = new DateTime(2008, 12, 28),
                    Price = 3.99M,
                    Sizes = new[] { "Small", "Medium", "Large" }
                };

            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            Console.WriteLine(json);

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
        }
    }

    internal class Product
    {
        public String[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}

結果

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}

ドキュメンテーション:オブジェクトをシリアル化する

おすすめ記事