.NET WebApi + DataTable
Asked Answered
A

2

6

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?

Anstice answered 28/1, 2013 at 21:52 Comment(0)
A
10

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;
    }
}
Anstice answered 29/1, 2013 at 20:1 Comment(1)
Thanks a lot. I asked the same question with bounty before i see this. If you there copy the answer link to my question i will give bounty to it.#39573943Piddle
C
0

Try putting [XmlElement] above Data.

Clipping answered 28/1, 2013 at 22:8 Comment(3)
Doesn't do much. I'm looking for a way to tell the JSON-formatter to leave the "Data"-string out.Anstice
What are you using to generate the JSON?Clipping
I am using the default JsonConverter of JSON.net. But I think I have to write a custom one to get what I wantAnstice

© 2022 - 2024 — McMap. All rights reserved.