一.Newtonsoft下载
首先需要下载Newtonsoft.json.dll,下载地址为https://github.com/JamesNK/Newtonsoft.Json/releases
选择相应的版本进行下载,解压后在bin文件夹中即可找到对应版本的Newtonsoft.json.dll文件。
二.Newtonsoft引用
接下来在项目中添加对Newtonsoft.json.dll进行引用。
- 右键单击解决方案资源管理器中的引用
- 选择添加引用
- 点击浏览,选择需要引用的dll文件
- 添加命名空间
using Newtonsoft.Json;
三.序列化Json集合
定义一个水果类作为示例
public enum Color
{
red,
green,
blue,
yellow
}
public class Fruit
{
public string Name { get; set; }
public float Price { get; set; }
public Color color { get; set; }
}
当拥有多个对象时,可将所有对象存储到List中,将List序列化即可。
//创建需要序列化的对象
Fruit apple = new Fruit()
{
Name = "apple",
Price = 5.9f,
color = Color.red,
};
Fruit banana = new Fruit()
{
Name = "banana",
Price = 6.9f,
color = Color.yellow
};
Fruit blueberry = new Fruit()
{
Name = "blueberry",
Price = 7.99f,
color = Color.blue
};
//将需要序列化的对象存储到List中
List<Fruit> fruits = new List<Fruit>();
fruits.Add(apple);
fruits.Add(banana);
fruits.Add(blueberry);
//序列化为Json格式
string json = JsonConvert.SerializeObject(fruits, Formatting.Indented);
//保存Json文件
if(!File.Exists("example.json"))
{
FileStream fs = new FileStream("example.json", FileMode.Create, FileAccess.ReadWrite);
fs.Close();
}
File.WriteAllText("example.json", json);
序列化后Json文件如下图所示:
四.Json文件反序列化
同样,首先需要先定义好反序列化后的对象,即上面的水果类。随后读取json文件进行反序列化。
//读取Json文件
string json = File.ReadAllText("example.json");
//反序列化
List<Fruit> fruits = JsonConvert.DeserializeObject<List<Fruit>>(json);
//打印信息
foreach(Fruit element in fruits)
{
Console.Write("Name: ");
Console.WriteLine(element.Name);
Console.Write("Price: ");
Console.WriteLine(element.Price);
Console.Write("color: ");
Console.WriteLine(element.color);
Console.WriteLine();
}
Console.ReadKey();
结果如下图所示: