C# Json读写

using Newtonsoft.Json; 

using Newtonsoft.Json.Linq;

 方法一:使用StreamReader/StringWriter


	//读取
	StreamReader file = File.OpenText(@"C:\Users\SAI\Desktop\czml.json");
	JsonTextReader reader = new JsonTextReader(file);
	JArray jArry = (JArray)JToken.ReadFrom(reader);//json数组
	if (jArry.Count == 0) return;
	JObject jsonObject = (JObject)jArry[0];
	jsonObject["name"] = "1111";

	//写入
	StringWriter sw = new StringWriter();
	JsonWriter writer = new JsonTextWriter(sw);
	jArry.WriteTo(writer);
	File.WriteAllText(@"C:\Users\SAI\Desktop\newJson.json", sw.ToString());

方法二:使用DeserializeObject/SerializeObject 


	//读取
	string json = File.ReadAllText(@"C:\Users\SAI\Desktop\czml.json");
	JArray jArry = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
	if (jArry.Count == 0) return;
	JObject jsonObject = (JObject)jArry[0];
	jsonObject["name"] = "1111";

	//写入
	string output = Newtonsoft.Json.JsonConvert.SerializeObject(jArry, Newtonsoft.Json.Formatting.Indented);//可以保持Json缩进
	File.WriteAllText(@"C:\Users\SAI\Desktop\newJson.json", output);

 

你可能感兴趣的:(C#)