Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serialize an object to C# object initializer code?

I'm looking to take an in-memory object (or JSON serialization of an object) and emit C# code to produce an equivalent object.

This would be useful for pulling known-good examples from a repository to use as starting points in unit tests. We have considered deserializing JSON, but C# code would have an edge when it comes to refactoring.

like image 229
Matthew Nichols Avatar asked Apr 26 '11 17:04

Matthew Nichols


People also ask

What is serialize C#?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What is serialization in C?

Serialization (C#) Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.

How do I serialize an object in a class?

In custom serialization, you can specify exactly which objects will be serialized and how it will be done. The class must be marked SerializableAttribute and implement the ISerializable interface. If you want your object to be deserialized in a custom manner as well, you must use a custom constructor.

What is the syntax used for serialization of an object?

For the serialization of the object in C#, an attribute called [Serializable]. If the attribute is not mentioned in a rightful manner, then at the run time a SerializableException is thrown. Below is the syntax used for serialization of object in C#: string aoo = "Heyoo!

How to read a serialized object back into memory?

The process of reading a serialized object back into memory is deserialization. In simple words serialization in C# is a process of storing the object instance to a persistant storage. Serialization stores state of objects i.e. member variable values to persostant storage such as a disk. Deserialization is reverse of serialization.


1 Answers

There is an interesting Visual Studio extension that addresses this; the Object Exporter. It allows serialization of an in-memory object into C# Object initialization code, JSON and XML. I haven't tried it yet but looks intriguing; will update after trying it out.

like image 154
Matthew Nichols Avatar answered Sep 22 '22 20:09

Matthew Nichols