0

I tried to convert DataTable to JSON string using JObject (NewtonSoft.dll). In my case table may have values with different data types. I want to convert those values to string while serialize the object.

        DataTable tab = new DataTable();
        tab.Columns.Add("ID", typeof(int));
        tab.Columns.Add("Name");

        tab.Rows.Add(1, "Role1");
        tab.Rows.Add(2, "Role2");

        string strValues = JsonConvert.SerializeObject(tab);
        --output of strValues 
        -- [{"ID":1,"Name":"Role1"},{"ID":2,"Name":"Role2"}]

But it should be like this -

[{"ID":"1","Name":"Role1"},{"ID":"2","Name":"Role2"}]

Please give me the solution. Thanks

3 Answers 3

2

You can use the third party .dll like Newtonsoft.Json

 DataTable tab = new DataTable();
 tab.Columns.Add("ID", typeof(int));
 tab.Columns.Add("Name");

 tab.Rows.Add(1, "Role1");
 tab.Rows.Add(2, "Role2");

 // Serialize to JSON string
 TextWriter output = new TextWriter();
 JsonTextWriter writer = new JsonTextWriter(output);
 writer.Formatting = JsonFormatting;
 JsonSerializer serializer = JsonSerializer.Create(JsonSerializerSettings);
 serializer.Serialize(writer, tab);
 writer.Flush();
Sign up to request clarification or add additional context in comments.

1 Comment

Im using newtonsoft only. I guess you misunderstood my question. I edited my question now. Please check
0

Why can't you just save the ID column as string, like this:

tab.Columns.Add("ID", typeof(string));

Or simply:

tab.Columns.Add("ID");

I don't see the purpose of saving it as an Int and then to try to convert it to a String...

2 Comments

I just showed this as sample. In real Im going to get the datatable from the database using ado.net and it may have multiple data type columns. Im asking for this scenario only.
I understand,converting the entire DataTable to string and then convert it to JSON, will help you? let me know if you need a sample.
0

The DataTableConverter which ships with Json.Net is not customizable in how it writes out its values. However, if you want integers (or any other value type) to be rendered as strings, you can easily make your own custom DataTableConverter to do what you want. Here is the code you would need:

class CustomDataTableConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(DataTable));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DataTable table = (DataTable)value;
        JArray array = new JArray();
        foreach (DataRow row in table.Rows)
        {
            JObject obj = new JObject();
            foreach (DataColumn col in table.Columns)
            {
                object val = row[col];
                obj.Add(col.ColumnName, val != null ? val.ToString() : string.Empty);
            }
            array.Add(obj);
        }
        array.WriteTo(writer);
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Use the converter like this:

string strValues = JsonConvert.SerializeObject(tab, new CustomDataTableConverter());

Fiddle: https://dotnetfiddle.net/mGMutp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.