2

In visual studio, is there a way to "serialize" an object to object-literal c# notation like you can serialize an object to json? I have numerous data objects that I currently get from a database that I would like to convert to literal objects to that I can include them in unit tests without relying on a database.

For example, if I have an instance of MyClass in memory, which has string properties Prop1, Prop2,... PropN, I'd like to serialize it to a string that looks like this c#:

var myClass1 = new MyClass(){
     Prop1 = "value 1",
     Prop2 = "value 2",
     ...
     PropN = "value n"
};
Rafe
  • 8,467
  • 8
  • 47
  • 67
  • There is no serializer like that, you'd have to write one using reflection. But you could serialize to XML and deserialize from XML in your unit tests using the `XmlSerializer`. – Marius Bancila May 05 '14 at 15:07
  • I don't know of any easy way. Perhaps not a duplicate, but close: http://stackoverflow.com/q/5793867 – default.kramer May 05 '14 at 15:07

2 Answers2

2

Perhaps your best option would be default XML serialization and then conversion to string.

XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); 
using (TextWriter writer = new StreamWriter(@"C:\myXml.xml"))
{
    serializer.Serialize(writer, details); 
} 

Then to retrieve the values:

TextReader reader = new StreamReader(@"D:\myXml.xml");
object obj = serializer.Deserialize(reader);
MyClass XmlData = (MyClass)obj;
reader.Close();

Of course you can play a lot with storing serialized classes in single files etc but then it becomes a file merging/splitting issue.

gerodim
  • 131
  • 8
-2

You should use:

JavaScriptSerializer

(Example included)

Abbas
  • 14,186
  • 6
  • 41
  • 72
Dzior
  • 1,485
  • 1
  • 14
  • 30
  • Maybe I wasn't clear enough - I don't want json output, I want c#. – Rafe May 05 '14 at 15:04
  • So basically you need to convert CLR object into the C# code that will construct and initialize this object with this values? Does the properties are only string? because if there not, it would be hard – Dzior May 05 '14 at 15:39