torsdag 4 december 2008

C# 3.0 Serialize anonymous types to JSON

Since C# 3.0 it's possible to create anonymous types. This can be pretty useful when serializing objects to JSON.

Let's say you have a Class with quite a few members, eg. Person, now you want to generate a json-array out of a generic list of these objects, however you are really only interested in a couple of properties (Name and ShoeSize) from the Person class.

You could of course create a SimplifiedPerson Class, and convert your List<Person> to a List<SimplifiedPerson>, eg:

   1:  List<Person> persons = GetPersons();
   2:  List<Simplifiedperson> simplifiedPersons =
   3:     persons.ConvertAll(person =>
   4:        new SimplifiedPerson(person.Name, person.ShoeSize));

However, if you are only going to use SimplifiedPerson in one context, you may want to consider using an anonymous type:

   1:  var simplifiedPersons = persons.ConvertAll(person => new {
   2:     Name = person.Name,
   3:     ShoeSize = person.ShoeSize
   4:  });

Finally, serialize your list to Json using your serializer of choice. I like the simplicity of the JavaScriptSerializer, and it works with anonymous types. However JavaScriptSerializer is obsolete but I don't think the suggested DataContractJsonSerializer can serialize anonymous types. see Rick Strahl's blog post about this topic.

   1:  JavaScriptSerializer serializer = new JavaScriptSerializer();
   2:  string json = serializer.Serialize(simplifiedPersons);

This is probably not news for many of you, but anyway, hope you'll find this useful :).

Bloggintresserade