Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để lấy JSON được định dạng trong .NET bằng C #?

Sử dụng Không gian tên Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting cung cấp các tùy chọn định dạng để Định dạng Json

Không có - Không có định dạng đặc biệt nào được áp dụng. Đây là mặc định.

Thụt lề - Làm cho các đối tượng con bị thụt vào theo cài đặt Newtonsoft.Json.JsonTextWriter.Indentation và Newtonsoft.Json.JsonTextWriter.IndentChar.

Ví dụ

static void Main(string[] args){
   Product product = new Product{
      Name = "Apple",
      Expiry = new DateTime(2008, 12, 28),
      Price = 3.9900M,
      Sizes = new[] { "Small", "Medium", "Large" }
   };
   string json = JsonConvert.SerializeObject(product, Formatting.Indented);
   Console.WriteLine(json);
   Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
   Console.ReadLine();
}
class Product{
   public String[] Sizes { get; set; }
   public decimal Price { get; set; }
   public DateTime Expiry { get; set; }
   public string Name { get; set; }
}

Đầu ra

{
   "Sizes": [
      "Small",
      "Medium",
      "Large"
   ],
   "Price": 3.9900,
   "Expiry": "2008-12-28T00:00:00",
   "Name": "Apple"
}

Ví dụ

static class Program{
   static void Main(string[] args){
      Product product = new Product{
         Name = "Apple",
         Expiry = new DateTime(2008, 12, 28),
         Price = 3.9900M,
         Sizes = new[] { "Small", "Medium", "Large" }
      };
      string json = JsonConvert.SerializeObject(product, Formatting.None);
      Console.WriteLine(json);
      Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
      Console.ReadLine();
   }
}
class Product{
   public String[] Sizes { get; set; }
   public decimal Price { get; set; }
   public DateTime Expiry { get; set; }
   public string Name { get; set; }
}

Đầu ra

{
   "Sizes": [
      "Small",
      "Medium",
      "Large"
   ],
   "Price": 3.9900,
   "Expiry": "2008-12-28T00:00:00",
   "Name": "Apple"
}