Json:
存储和交换文本信息的语法。(类似XML,语法独立)
一种轻量级的数据交换格式。(更小,更快,更易解析)
语法规则:
数据在键值对里面,数据由逗号分隔开。
用花括号保存对象,用方括号保存数组。
Josn值:
数字(整型或浮点型)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在方括号中)
null
// skill.json
[
{
"id": 1,
"name": "zhongji",
"damage": 200
},
{
"id": 2,
"name": "huixuanzhan",
"damage": 300
},
{
"id": 1,
"name": "sanduansha",
"damage": 500
}
]
//Hero.json
{
"name": "Huozhong",
"maxHP": 15000,
"type": "Marksman",
"skillList": [
{
"id": 1,
"name": "zhongji",
"damage": 200
},
{
"id": 2,
"name": "huixuanzhan",
"damage": 300
},
{
"id": 1,
"name": "sanduansha",
"damage": 500
}
]
}
// Skill.cs
class Skill
{
public int id { get; set; }
public string name { get; set; }
public int damage { get; set; }
}
// Hero.cs
class Hero
{
public string Name { get; set; }
public int MaxHP { get; set; }
public string Type { get; set; }
public List SkillList { get; set; }
}
// Program.cs
class Program
{
static void Main(string[] args)
{
// 定义一个Skill类的数组,将skill.json文件字符串反序列化(json字符串转换为一个字符串类对象)
Skill[] skillArray = JsonConvert.DeserializeObject(File.ReadAllText("skill.json"));
foreach (Skill s in skillArray)
{
Console.WriteLine(s.id + "," + s.name + "," + s.damage);
/*
1,zhongji,200
2,huixuanzhan,300
1,sanduansha,500
*/
}
// 自定义一个Skill类对象
Skill skill = new Skill
{
id = 10,
name = "Smith",
damage = 1000
};
// 对象的序列化,将对象序列化为JSON字符串
string str = JsonConvert.SerializeObject(skill);
Console.WriteLine(str); // {"id":10,"name":"Smith","damage":1000}
// 定义一个字符串数组
string[] names = { "张三", "李四", "王五" };
string str1 = JsonConvert.SerializeObject(names);
Console.WriteLine(str1); // ["张三","李四","王五"]
Hero hero = JsonConvert.DeserializeObject(File.ReadAllText("Hero.json"));
Console.WriteLine(hero.Name); // Huozhong
Console.WriteLine(hero.MaxHP); // 15000
Console.WriteLine(hero.Type); // Marksman
foreach (Skill s in hero.SkillList)
{
Console.WriteLine(s.id + ", " + s.name + ", " + s.damage);
/*
1, zhongji, 200
2, huixuanzhan, 300
1, sanduansha, 500*/
}
}
}
// 运行结果