先建一個HELP.json檔在執行檔路徑
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
}
再建一個類別檔
public class datamodel
{
public string key1 { get; set; }
public string key2 { get; set; }
public string key3 { get; set; }
}
json反序列化 HELP.json檔 ,建的類別只有3屬性,因此key4會忽略掉
string path = Path.Combine(Environment.CurrentDirectory, "HELP.json"); //"Debug"資料夾路徑
StreamReader sr = new StreamReader(path, true);
string jsonString = sr.ReadToEnd();
datamodel dm = JsonSerializer.Deserialize<datamodel>(jsonString);
Console.WriteLine(dm.key1 + dm.key2 + dm.key3);
json反序列化到HELP2.json檔
JsonSerializerOptions options = new JsonSerializerOptions()
{
WriteIndented = true//格式化json資料,排版比較好看
};
string jsonString2 = JsonSerializer.Serialize(dm, options);
string path2 = Path.Combine(Environment.CurrentDirectory, "HELP2.json"); //"Debug"資料夾路徑
StreamWriter sw = new StreamWriter(path2);
sw.WriteLine(jsonString2);
點擊HELP2.json就有格式化好的key1~key3內容了