.NET WebApi DataTable
发布时间:2020-12-16 19:49:32 所属栏目:百科 来源:网络整理
导读:我正在构建一个.NET WebApi项目.我的一个ApiControllers返回一个数据表.在JSON格式中,它看起来都很好,但XML格式包含了我不需要的垃圾. 所以,我在想,让我们编写自己的XML序列化.为此,我创建了一个实现IXmlSerializable的新类.它看起来像这样: public class M
我正在构建一个.NET WebApi项目.我的一个ApiControllers返回一个数据表.在JSON格式中,它看起来都很好,但XML格式包含了我不需要的垃圾.
所以,我在想,让我们编写自己的XML序列化.为此,我创建了一个实现IXmlSerializable的新类.它看起来像这样: public class MyDataTable : IXmlSerializable { public MyDataTable(DataTable datatable) { this.Data = datatable; } public void WriteXml(XmlWriter writer) { writer.WriteStartElement("Test"); writer.WriteElementString("T","hello world"); writer.WriteEndElement(); } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { throw new NotImplementedException(); } public DataTable Data { get; set; } } 现在我的XML看起来很棒,但我的JSON不是. {"Data":[{"id":1,"name":"John"},{"id":2,"name":"Julia"}]} 我真正想要的是: [{"id":1,"name":"Julia"}] 有没有一种简单的方法可以从JSON结果中删除“Data”字符串,而无需重写整个内容?
我已经编写了自己的数据表序列化来实现我的目标.
感兴趣的人: [JsonConverter(typeof(DataTableConverter))] [XmlRoot("Result")] public class MyDataTable : IXmlSerializable { public MyDataTable(DataTable datatable) { this.Data = datatable; } public void WriteXml(XmlWriter writer) { foreach (DataRow row in Data.Rows) { writer.WriteStartElement(Data.TableName); foreach (DataColumn column in row.Table.Columns) { writer.WriteElementString(column.ColumnName,row[column].ToString()); } writer.WriteEndElement(); } } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { throw new NotImplementedException(); } public DataTable Data { get; set; } } 和自定义JSON转换器: public class DataTableConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(MyDataTable).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer) { MyDataTable myDataTable = value as MyDataTable; DataTable dt = myDataTable.Data; writer.WriteStartArray(); foreach (DataRow row in dt.Rows) { writer.WriteStartObject(); foreach (DataColumn column in row.Table.Columns) { writer.WritePropertyName(column.ColumnName); serializer.Serialize(writer,row[column]); } writer.WriteEndObject(); } writer.WriteEndArray(); } } 像这样实现新的DataTable类: public class ValuesController : ApiController { // GET api/values public MyDataTable Get() { DataTable dt = new DataTable(); dt.TableName = "info"; using (SqlConnection cn = new SqlConnection("Data Source=(local);Initial Catalog=ApiPoc;Integrated Security=true;")) { cn.Open(); using (SqlCommand cm = new SqlCommand("select * from employee",cn)) { SqlDataReader dr = cm.ExecuteReader(); dt.Load(dr); } } MyDataTable md = new MyDataTable(dt); return md; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |