Json基本语法:
json数据结构:
代码事例:
//program.cs
using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
namespace JsonStudy
{
class Program
{
static void Main(string[] args)
{
List skillList = JsonMapper.ToObject>(File.ReadAllText("SkillInfo.txt"));
foreach (var tmp in skillList)
{
Console.WriteLine(tmp);
}
}
}
}
//SkillInfo.txt
[
{"id":1,"name":"龙闪","level":1},
{"id":2,"name":"居合","level":1},
{"id":3,"name":"一字斩","level":1}
]
//Skill.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace JsonStudy
{
class Skill
{
public int id;
public string name;
public int level;
public Skill(int id, string name, int level)
{
this.id = id;
this.name = name;
this.level = level;
}
public override string ToString()
{
return string.Format("id:{0},name:{1},level:{2}", id, name, level);
}
}
}
注意Skill类要和相应的txt文件每个元素保持一致(文件名等)
实例2:
//Program.cs
using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
namespace JsonStudy
{
class Program
{
static void Main(string[] args)
{
Player player = JsonMapper.ToObject(File.ReadAllText("PlayerInfo.txt"));
Console.WriteLine(player);
foreach (var tmp in player.skillList)
{
Console.WriteLine(tmp);
}
}
}
}
//PlayerInfo.txt
{
"name":"tqt",
"level":1,
"skillList":
[
{"id":1,"name":"龙闪","level":1},
{"id":2,"name":"居合","level":1},
{"id":3,"name":"一字斩","level":1}
]
}
//Player.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace JsonStudy
{
class Player
{
public string name;
public int level;
public List skillList;
public override string ToString()
{
return string.Format("name:{0},level:{1}", name, level);
}
}
}
也可以将我们构造的对象转化成json字符串:
//Program.cs
using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
namespace JsonStudy
{
class Program
{
static void Main(string[] args)
{
Player player = new Player();
player.name = "tqt";
player.level = 1;
Skill skill1 = new Skill(1, "龙闪", 1);
Skill skill2 = new Skill(2, "居和", 1);
player.skillList = new List();
player.skillList.Add(skill1);
player.skillList.Add(skill2);
string jsonString = JsonMapper.ToJson(player);
Console.WriteLine(jsonString);
}
}
}