简体   繁体   中英

Convert Datatable to JSON without table header

I'm trying to convert a datatable to JSON. I can get it but the problem is I'm getting property names corresponding to header of the table in serialization result string:

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

This returns a string:

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

but I don't need property names in the string, I just need :

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

You need to implement and use custom JavaScriptConverter . In your case it could look like this:

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

Then you need to register it in your serializer, before you call serialization routine:

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

Then you will get output like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM