JavaScriptSerializer serializes types derived from IEnumerable as JavaScript arrays. It convenient for arrays and lists but in some cases I need to serialize properties declared in derived type (e.g. Key in IGrouping). Here some sample code:
var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
IGrouping<char, string> data = items.GroupBy(i => i[0]).First();
var serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(data);
// serialized == "[\"aaabbb\",\"abcd\"]"
// doesn't contain definition for IGrouping.Key property
Is there any simple solution for this problem?
You could try this:
var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
var data = (from x in items
group x by x[0] into g
select new
{
Key = g.Key,
Value = g
}).First();
var serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(data);
or if you prefer:
var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
var data = items.GroupBy(i => i[0])
.Select(x => new { Key = x.Key, Value = x })
.First();
var serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(data);
In both cases the result would be:
{"Key":"a","Value":["aaabbb","abcd"]}
Check out JSON.NET. I've used it on a couple of projects and it makes JSON serialization and deserialization a lot easier. It will serialize most objects with a single method call, and also lets you have a finer-grained control over the serialization with custom attributes.
Here's a sample from the author's website:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With