.NET WebApi + DataTable [英] .NET WebApi + DataTable

查看:1101
本文介绍了.NET WebApi + DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个.NET WebApi项目。我的一个ApiController返回一个datatable。在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,你好世界);
writer.WriteEndElement();
}

public XmlSchema GetSchema()
{
return null;
}

public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}

public DataTable Data {get;组; }
}

现在我的XML看起来不错,但是我的JSON不是。
JSON看起来像:

  {Data:[{id:1,name John},{id:2,name:Julia}]} 

我真正想要的是:

  [{id:1,name:John},{ id:2,name:Julia}] 

有没有一个简单的方法从JSON结果中删除数据 - 字符串,而不是重写整个事情?
或者有比这更好的解决方案吗?

解决方案

我已经编写了自己的datatable序列化来实现我的目标



对于感兴趣的人:

  [JsonConverter(typeof DataTableConverter))
[XmlRoot(Result)]
public class MyDataTable:IXmlSerializable
{
public MyDataTable(DataTable datatable)
{
this .Data = datatable;
}


public void WriteXml(XmlWriter writer)
{
foreach(Data.Rows中的DataRow行)
{
writer.WriteStartElement(Data.TableName);
foreach(row.Table.Columns中的DataColumn列)
{
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;组; }
}

和一个自定义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(dt.Rows中的DataRow行)
{
writer.WriteStartObject();
foreach(row.Table.Columns中的DataColumn列)
{
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;
}
}


I'm building a .NET WebApi project. One of my ApiControllers returns a datatable. In JSON format, it all looks good, but the XML-format contains so much junk I don't need.

So, I was thinking, let's write my own XML-serialization. For doing this I've made a new class that implements IXmlSerializable. It looks like this:

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; }
}

Now my XML looks great, but my JSON isn't. The JSON looks like:

{"Data":[{"id":1,"name":"John"},{"id":2,"name":"Julia"}]}

What I really want is this:

[{"id":1,"name":"John"},{"id":2,"name":"Julia"}]

Is there an easy way to remove the "Data"-string from the JSON-result, without rewriting the whole thing? Or is there a better solution than this one?

解决方案

I have written my own datatable serialization to achieve my goal.

For the interested folk:

[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; }
}

And a custom JSON converter:

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();
    }
}

Implement the new DataTable class like this:

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;
    }
}

这篇关于.NET WebApi + DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆