配置json环境有俩种方法,一种是直接去官网下载包,导进vs中,一种是直接在vs中在线安装,自动配置(这里介绍第二种,直接上图)
在工程视图中右键引用,点击管理NuGet程序包
搜索litjson,然后下载安装即可
[
{"id":2,"name":"天下无双","damage":123},
{"id":3,"name":"天下无贼","damage":23},
{"id":4,"name":"咫尺天涯","damage":900}
]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSON解析
{
class Skill
{
public int id;
public int damage;
public string name;
public override string ToString()
{
return string.Format("Id:{0},Damage:{1},Name:{2}", id, damage, name);
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
namespace JSON解析
{
class Program
{
static void Main(string[] args)
{
List skilllList = new List();
//使用jsonmapper去解析json文本
//jsondata代表一个数组或者一个对象
//在这里jsondata代表一个数组
JsonData jsonData = JsonMapper.ToObject(File.ReadAllText("json.txt"));
foreach (JsonData tempData in jsonData)//这里的temp代表一个对象
{
Skill skill = new Skill();
JsonData idValue = tempData["id"];//通过字符索引器可以取得键值对的值
JsonData nameValue = tempData["name"];
JsonData damageValue = tempData["damage"];
int id = int.Parse(idValue.ToString());
int damage = int.Parse(damageValue.ToString());
Console.WriteLine(id + ":" + nameValue.ToString() + ":" + damage);
skill.id = id;
skill.damage = damage;
skill.name = nameValue.ToString();
skilllList.Add(skill);
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
namespace JSON解析
{
class Program
{
static void Main(string[] args)
{
//使用泛型去解析json文件
Skill[] skillArray = JsonMapper.ToObject(File.ReadAllText("json.txt"));//使用这种方法,泛型类的字段,属性必须为public,而且字段名,顺序必须与json文件中对应
foreach (var temp in skillArray)
{
Console.WriteLine(temp);
}
List skilllList = JsonMapper.ToObject>(File.ReadAllText("json.txt"));
foreach (var temp in skilllList)
{
Console.WriteLine(temp);
}
}
}
}
{
"Name":"lala",
"Level":99,
"Age":18,
"SkillList":[
{"id":2,"name":"天下无双","damage":123},
{"id":3,"name":"天下无贼","damage":23},
{"id":4,"name":"咫尺天涯","damage":900}
]
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSON解析
{
class Player
{
public string Name { get; set; }
public int Level { get; set; }
public int Age { get; set; }
public List SkillList { get; set; }
public override string ToString()
{
return string.Format("Name:{0},Level:{1},Age:{2},SkillList:{3}", Name, Level, Age,SkillList);
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
namespace JSON解析
{
class Program
{
static void Main(string[] args)
{
Player p = JsonMapper.ToObject(File.ReadAllText("敌人.txt"));//json文件向类的转化
Console.WriteLine(p);
//将一个对象转换成json
Player p = new Player();
p.Name = "www";
p.Level = 99;
p.Age = 14;
string s = JsonMapper.ToJson(p);
Console.WriteLine(s);
}
}
}