作者:阳光美女新干线- | 来源:互联网 | 2023-09-16 13:01
▲读写的文件XiaoMing.json:{Name:小明,Sex:男,Age:12}JsonWriteTest.json:{StartX:1.23,StartY:1.24,EndX
▲ 读写的文件
XiaoMing.json:
{"Name":"小明","Sex":"男","Age":12}
JsonWriteTest.json:
{
"StartX": 1.23,
"StartY": 1.24,
"EndX": 10,
"EndY": "YY",
"Favorites": [
"吃饭",
"睡觉"
],
"Remark": null
}
引入 Newtonsoft.Json.dll
。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ReadJsonFile();
WriteJson();
Console.ReadKey();
}
private static void ReadJsonFile()
{
string jFileName = "./XiaoMing.json";
StreamReader sr = File.OpenText(jFileName);
JsonTextReader jr = new JsonTextReader(sr);
JObject jObj = JToken.ReadFrom(jr) as JObject;
Console.WriteLine($"Name:{jObj["Name"].Value()} \nSex:{jObj.Value("Sex")} \nAge:{jObj["Age"].Value()}");
}
private static void WriteJson()
{
string fileName = "./JsonWriteTest.json";
JObject jsonObj1 = new JObject();
jsonObj1["StartX"] = 1.23;
jsonObj1["StartY"] = 1.24;
jsonObj1["EndX"] = 10;
jsonObj1["EndY"] = "YY";
// 创建数组
JArray array = new JArray();
array.Add(new JValue("吃饭"));
array.Add(new JValue("睡觉"));
jsonObj1.Add("Favorites", array);
jsonObj1.Add("Remark", null);
//Console.WriteLine(array.ToString());
string cOnvertString= Convert.ToString(jsonObj1);//将json装换为string
File.WriteAllText(fileName, convertString, System.Text.Encoding.UTF8);//将内容写进jon文件中
}
}
}
参考:
- https://www.cnblogs.com/dangnianxiaoqingxin/p/13365820.html // C# 使用Newtonsoft.Json读写Json文件
- C# Newtonsoft.Json用法 https://blog.csdn.net/qq_38693757/article/details/113728350
- https://www.jb51.net/article/204058.htm // C# Newtonsoft.Json 解析多嵌套json 进行反序列化的实例
- https://www.jb51.net/article/256530.htm // c#解析jobject的数据结构