[研究][ASP.NET]用 Newtonsoft.Json 套件建立 .json 檔案
2024-01-10
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#
********************************************************************************
Default.aspx.cs 使用 Newtonsoft.Json
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// 建立一個示例資料物件
var dataObject = new
{
Name = "John Doe",
Age = 30,
Email = "john.doe@example.com"
};
// 將物件轉換為 JSON 字串
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dataObject);
// 指定要儲存的 JSON 檔案路徑
string filePath = Server.MapPath("~/data.json");
// 將 JSON 字串寫入檔案
File.WriteAllText(filePath, jsonString);
Response.Write($"JSON 檔案已建立:{filePath}");
}
}
}
|
********************************************************************************
2024-01-11補
默認情況下它會將整個 JSON 放在單一行中。如果您想要格式化 JSON 字串以便易讀,您可以使用Formatting.Indented選項。以下是修改後的程式碼:
Default.aspx.cs 使用 Newtonsoft.Json
// 將物件轉換為格式化的 JSON 字串
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dataObject, Newtonsoft.Json.Formatting.Indented);
|
(完)
相關


沒有留言:
張貼留言