【C#】C#操作Json文件 LitJson

 

使用LitJson解析Json

可以通过NuGet安装LitJson包

直接添加引用

LitJSON.dll下载

链接:https://pan.baidu.com/s/1IsGPE4FFFWtS7wk1FzOg4w 
提取码:un7p 
 

下面创建一个StudentsInfo.json文件进行测试

[
  {
    "ID": 1001,
    "Name": "哈哈",
    "Class": "1"
  },
  {
    "ID": 1002,
    "Name": "啊啊",
    "Class": "2"
  },
  {
    "ID": 1003,
    "Name": "嘻嘻",
    "Class": "1"
  }
]

创建Model

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }

    public string Class { get; set; }

    public override string ToString()
    {
        return string.Format("ID:{0},Name:{1},Class:{2}", ID, Name, Class);
    }
}

读取解析Josn

//获取Josn数据
JsonData data = JsonMapper.ToObject(File.ReadAllText("StudentsInfo.json"));

List stuList = new List();

foreach (JsonData item in data)
{
    Student stu = new Student();
    stu.ID = int.Parse(item["id"].ToString());
    stu.Name = item["name"].ToString();
    stu.Class = item["class"].ToString();

    stuList.Add(stu);
}

//输出
foreach (var stu in stuList)
{
    Console.WriteLine(stu.ToString());
}

使用泛型获取Josn数据,更加方便

注意Json数据名称要与Model属性名称相同

List < Student > stuList = JsonMapper.ToObject>(File.ReadAllText("StudentsInfo.json"));

//输出
foreach (var stu in stuList)
{
    Console.WriteLine(stu.ToString());
}

输出

 

上面的Josn数据是一个数组,如果是一个对象呢,即一个学生的信息

Json文件

{
  "ID": 1001,
  "Name": "哈哈",
  "Class": "1",
  "CourseList": [
    {
      "ID": 501,
      "Name": "语文"
    },
    {
      "ID": 502,
      "Name": "数学"
    }
  ]
}

创建Model

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }

    public string Class { get; set; }

    public List CourseList { get; set; }

    public override string ToString()
    {
        return string.Format("ID:{0},Name:{1},Class:{2}", ID, Name, Class);
    }
}

public class Course
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return string.Format("ID:{0},Name:{1}", ID, Name);
    }
}

解析Json

//使用泛型获取Josn数据
Student stu = JsonMapper.ToObject(File.ReadAllText("StudentsInfo.json"));

//输出
Console.WriteLine(stu.ToString());
foreach (var course in stu.CourseList)
{
    Console.WriteLine(course.ToString());
}

输出

 

对象转Josn

Student stu = new Student() { ID = 110,Name ="呵呵",Class = "101"};

string json = JsonMapper.ToJson(stu);

Console.WriteLine(json);

输出

其中Name值转成了Unicode编码

 

相关链接:

Json校验格式化工具: http://www.bejson.com/

Josn编辑器: http://www.bejson.com/jsoneditoronline/

 

你可能感兴趣的:(C#操作Xml/Json)