.NET WebApi + 数据表 [英] .NET WebApi + DataTable

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

问题描述

我正在构建一个 .NET WebApi 项目.我的一个 ApiControllers 返回一个数据表.在 JSON 格式中,一切看起来都不错,但是 XML 格式包含了太多我不需要的垃圾.

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.

所以,我在想,让我们编写自己的 XML 序列化.为此,我创建了一个实现 IXmlSerializable 的新类.它看起来像这样:

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

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

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

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

我真正想要的是:

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

有没有一种简单的方法可以从 JSON 结果中删除数据"字符串,而无需重写整个内容?或者还有比这更好的解决方案吗?

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.

感兴趣的人:

[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 转换器:

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

像这样实现新的 DataTable 类:

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 + 数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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