C#利用Newtonsoft.Json.dll讀寫JSON文件
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
附件:Newtonsoft.Json.rar
1、在項(xiàng)目中添加以上引用:
2、新建一個(gè)config.json文件(名字隨意):
{
"userInfo": {
"customerName": "123456",
"sex": "男",
"age": "49",
"time": "2017-01-18 10:30 巳時(shí)",
"quality": "86.5",
"siteName": "醫(yī)療機(jī)構(gòu)/健康會(huì)所"
},
"thermalStructure": {
"valRen": 3,
"valDu": 2,
"tripleEnergizer": [
-0.5,
3,
1.5
],
"viscera": [
-0.5,
3,
1,
2.5,
3,
2,
2,
1.5,
3,
2.5,
3.2,
3,
0.5,
0,
1,
1.5
]
},
"date": "2020-01-02"
} 3、讀取Json代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
//記得引用這幾個(gè)玩意
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace 操作json與xml
{
class ReadJson
{
public static string Get_server()
{
try
{
StreamReader reader = File.OpenText("config.json");
JsonTextReader jsonTextReader = new JsonTextReader(reader);
JObject jsonObject = (JObject)JToken.Readfrom(jsonTextReader);
string server = jsonObject["server"].ToString(); //user ,passwd 類似
reader.Close();
return server;
}
catch
{
//自己加點(diǎn)
}
}
}
}
4、寫入代碼:
public static void Set_server(string server)
{
try
{
StreamReader reader = File.OpenText("config.json");
JsonTextReader jsonTextReader = new JsonTextReader(reader);
JObject jsonObject = (JObject)JToken.Readfrom(jsonTextReader);
jsonObject["server"] = server; //user ,passwd 類似
reader.Close();
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("config.json", output);
}
catch
{
//自己加點(diǎn)
}
} 該文章在 2022/8/9 0:14:50 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |