将Datatable转换为JSON而不使用表头

时间:2014-05-26 09:56:17

标签: c# sql json datatable

我正在尝试将数据表转换为JSON。我可以得到它,但问题是我在序列化结果字符串中得到与表头相对应的属性名称:

private string TestForEach(DataTable table)
    {
        var categoryList = new List<FilterCountry>(table.Rows.Count);
        foreach (DataRow row in table.Rows)
        {
            var values = row.ItemArray;
            var category = new FilterCountry()
            {
                Country = values[0].ToString(),
                Count = (Int32)values[1]
            };
            categoryList.Add(category);
        }
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Serialize(categoryList);
    }

返回一个字符串:

[{"Count":2,"Country":"China"},{"Count":3,"Country":"India"},{"Count":3,"Country":"Pakistan"},{"Count":5,"Country":"United Arab Emirates"}]

但我不需要字符串中的属性名称,我只需要:

"China":2,"India":3,"Pakistan":3,"United Arab Emirates":5

1 个答案:

答案 0 :(得分:0)

您需要实施并使用custom JavaScriptConverter。在你的情况下,它可能看起来像这样:

public class FilterCountryListConverter : JavaScriptConverter
{
   public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
   {
       throw new NotImplementedException();
   }

   public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
   {
       var output = new Dictionary<string, object>();
       List<FilterCountry> filters = obj as List<FilterCountry>;
       filters.ForEach( f => output.Add( f.Country, f.Count ) );
       return output;
   }

   public override IEnumerable<Type> SupportedTypes
   {
       get { return new List<Type>(new List<Type>(new Type[] { typeof(List<FilterCountry>) }));  }
   }
}

然后,在调用序列化例程之前,需要在序列化程序中注册它:

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new FilterCountryListConverter() });
var res = serializer.Serialize(categoryList);

然后你会得到如下输出:

{"China":2,"India":2,"Pakistan":3,"United Arab Emirates":5}