Serialize to C# Initializer code instead of to JSON?

Jul 13, 2012 at 1:19 PM

Hello,

I'm wondering if JSON.NET does, or could easily be extended, to serialize and in-memory object graph to a literal C# object initializer, provided the graph is nothing but a collection of poco/dto objects?

Something like the questioner and the sample code on this thread does:

http://stackoverflow.com/questions/5793867/is-there-a-tool-to-serialize-an-object-to-c-sharp-object-initializer-code

Here's the scenario:

Below are a couple of classes and a method that instantiates and manually populates data into them. Below that is what I'd like as the "serializer" output.

I'd like to serialize messages (dtos) that come into and out of a system and save those as a script. If someone ever modified the message signatures, it would thus fail the test build, which is what I'd like to happen.

 

I think I could get the code on stackoverflow to work, but right now it's not doing well with generics, so I was just wondering if anyone had attempted something like this with JSON.NET as an extension or in general.


public class Container { public string Label { get; set; } public IList<Element<string>> Elements { get; set; } } public class Element<T> { public T Data { get; set; } }
public void TestData() { var container = new Container(); container.Label = "Label"; container.Elements = new List<Element<string>>(); var element = new Element<string>(); element.Data = "one"; container.Elements.Add(element); element = new Element<string>(); element.Data = "two"; container.Elements.Add(element);
}

public void SerializedAsInitializerCode() { var container = new Container { Label = "Label", Elements = new List<Element<string>>() { new Element<string> { Data = "one" }, new Element<string> { Data = "two" } } }; }