views:

378

answers:

2

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?

A: 

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"]}
Darin Dimitrov
I've got your idea, but I'm looking for a common solution with support of all types derived from IEnumerable: ICollection, IGrouping, ILookup and even custom user types
altso
+1  A: 

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);
Colin Cochrane