我正在构建一个.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结果中删除“Data”字符串,而无需重写整个内容? 或者有比这更好的解决方案吗?
答案 0 :(得分:9)
我已经编写了自己的数据表序列化来实现我的目标。
感兴趣的人:
[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;
}
}
答案 1 :(得分:0)
尝试将[XmlElement]放在Data
上方。