Convert Int to String while serialize object using JSON.NET

江枫思渺然 提交于 2020-01-17 05:30:10

问题


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


回答1:


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



回答2:


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...




回答3:


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



来源:https://stackoverflow.com/questions/37475997/convert-int-to-string-while-serialize-object-using-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!