C#中对json文件的读写

  |  
阅读次数 
  

C#(winform)对json文件的读写

需要引用 Newtonsoft,读文件时若文件为空则至少保留一对{}否则会抛出异常

读文件并返回相关key值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public string readJson(string key)
{
try
{
string fp = new DirectoryInfo("../../").FullName + "info.json";
StreamReader file = File.OpenText(fp);
JsonTextReader reader = new JsonTextReader(file);
JObject jsonObject = (JObject)JToken.ReadFrom(reader);
file.Close();
return (string)jsonObject[key];
}catch(Exception ex)
{
throw new Exception(ex.Message);
}

}

写文件(传入key和value)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void writeJson(string key,string value) {
try
{
string fp = new DirectoryInfo("../../").FullName + "info.json";
string json = File.ReadAllText(fp);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
if(jsonObj[key] != null)
{
jsonObj[key] = value;
}else
{
jsonObj.Add(new JProperty(key,value));
}
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(fp,output);


}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}