我正在构建一个.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":"John"},{"id":2,"name":"Julia"}]
有没有一种简单的方法可以从 JSON 结果中删除"数据"字符串,而无需重写整个内容?还是有比这个更好的解决方案?
我已经编写了自己的数据表序列化来实现我的目标。
对于感兴趣的人:
[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;
}
}
尝试将 [XmlElement] 放在 Data
之上。