c# 对json数据的处理
时间:2010-10-06 来源:Ron
刚接触下json发现这东西也挺有意思的,就用c#做个例子玩玩,在此记录下
json数据格式:
{"Id":20547,"Name":"中南大学","NameEn":"central-south university","AreaId":190},{"Id":20548,"Name":"湖南大学","NameEn":"Hunan university","AreaId":190},{"Id":20549,"Name":"湖南师范大学","NameEn":"hunan normal university","AreaId":190}
首先还是介绍下实体类吧,在这切记类名和json的大小写什么的都要一致。
public class School
{
[System.Runtime.Serialization.DataMember]
public string Id { get; set; }
[System.Runtime.Serialization.DataMember]
public string Name { get; set; }
[System.Runtime.Serialization.DataMember]
public string NameEn { get; set; }
[System.Runtime.Serialization.DataMember]
public string AreaId { get; set; }
}
获取单单一条结果集我参考了下别人的写法:
public static School getOneJson(string jsonText)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(School));
return (School)serializer.ReadObject(ms);
}
}
获取多条的找了下没发现,也就懒得深找了,自己随意些了个,反正能得到值,效率什么的还是以后真正用的时候研究把。
public static List<School> getOneJson(string jsonText)
{
List<School> list = new List<School>();
JavaScriptSerializer js = new JavaScriptSerializer();
object obj = js.DeserializeObject(jsonText);
foreach (object item in ((object[])(js.DeserializeObject(jsonText))))
{
School model = new School();
model.Id = ((Dictionary<string, object>)item)["Id"].ToString();
model.Name = ((Dictionary<string, object>)item)["Name"].ToString();
model.NameEn = ((Dictionary<string, object>)item)["NameEn"].ToString();
model.AreaId = ((Dictionary<string, object>)item)["AreaId"].ToString();
list.Add(model);
}
return list;
}