1、定义
Json是轻量级的文本数据交换格式;
Json具有自我描述性,更易理解;
Json比Xml更小、更快、更易解析;
Json跟Xml一样是一种数据格式。
2、语法规则
3、C#中进行XML操作
1、在VS中新建一个文本文档“Json技能信息”;
2、右键选择打开方式为“JSON编辑器”;
3、使用LitJson解析文本;
[
{"id": 1,"name": "无情冲锋","damage": 55},
{"id": 2,"name": "背水一战","damage": 80},
{"id": 3,"name": "国士无双","damage": 140}
]
using System;
using LitJson;
using System.IO;
using System.Collections.Generic;
/*
* Json操作
* 2020/4/13
* 引用LitJson
* 使用JsonMapper解析Json文档
*/
namespace Json操作
{
class Program
{
static void Main(string[] args)
{
//方法1
List<Skill> skillList = new List<Skill>();
//JsonData代表一个数组或者一个对象,在这里代表一个数组
JsonData jsonData = JsonMapper.ToObject(File.ReadAllText("Json技能信息.txt"));
foreach (JsonData temp in jsonData)
{
Skill skill = new Skill();
//通过字符串索引器可以获得键值对的值
JsonData idValue = temp["id"];
JsonData nameValue = temp["name"];
JsonData damageValue = temp["damage"];
int id = Int32.Parse(idValue.ToString());
int damage = Int32.Parse(damageValue.ToString());
//Console.WriteLine(id+":"+nameValue+":"+damage+";");
skill.id = id;
skill.name = nameValue.ToString();
skill.damage = damage;
skillList.Add(skill);
}
foreach (Skill info in skillList)
{
Console.WriteLine(info);
}
//方法2
//Skill[] skillArray = JsonMapper.ToObject<Skill[]>(File.ReadAllText("Json技能信息.txt"));
//foreach(Skill info in skillArray)
//{
// Console.WriteLine(info);
//}
Console.ReadKey();
}
}
}
namespace Json操作
{
class Skill
{
public int id;
public string name;
public int damage;
public override string ToString()
{
return string.Format("ID:{0}, Name:{1},Damage:{2}", id, name, damage);
}
}
}
4、Json在线编辑器
http://www.bejson.com/jsoneditoronline/