Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON: Serializing types derived from IEnumerable

Tags:

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?

like image 418
altso Avatar asked Sep 19 '09 18:09

altso


2 Answers

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"]}
like image 189
Darin Dimitrov Avatar answered Sep 24 '22 21:09

Darin Dimitrov


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);
like image 27
Colin Cochrane Avatar answered Sep 25 '22 21:09

Colin Cochrane