使用LitJson解析Json
或
LitJSON.dll下载
链接:https://pan.baidu.com/s/1IsGPE4FFFWtS7wk1FzOg4w
提取码:un7p
[
{
"ID": 1001,
"Name": "哈哈",
"Class": "1"
},
{
"ID": 1002,
"Name": "啊啊",
"Class": "2"
},
{
"ID": 1003,
"Name": "嘻嘻",
"Class": "1"
}
]
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数据
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());
}
注意Json数据名称要与Model属性名称相同
List < Student > stuList = JsonMapper.ToObject>(File.ReadAllText("StudentsInfo.json"));
//输出
foreach (var stu in stuList)
{
Console.WriteLine(stu.ToString());
}
输出
{
"ID": 1001,
"Name": "哈哈",
"Class": "1",
"CourseList": [
{
"ID": 501,
"Name": "语文"
},
{
"ID": 502,
"Name": "数学"
}
]
}
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);
}
}
//使用泛型获取Josn数据
Student stu = JsonMapper.ToObject(File.ReadAllText("StudentsInfo.json"));
//输出
Console.WriteLine(stu.ToString());
foreach (var course in stu.CourseList)
{
Console.WriteLine(course.ToString());
}
输出
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/