我正在构建一个.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不是.
JSON看起来像:
{"Data":[{"id":1,"name":"John"},{"id":2,"name":"Julia"}]}
我真正想要的是:
[{"id":1,"name":"Julia"}]
我已经编写了自己的数据表序列化来实现我的目标.
原文链接:https://www.f2er.com/json/288536.html感兴趣的人:
[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; } }