4

Is there any way to serialize an anonymous type in .net? Normal XmlSerializer fails because the type has no parameterless constructor defined; and NetDataContractSeralizer fails becuase we can't tag DataContract or Serializable attribute to anonymous class.

So is there any clever way around or we just can't do it?

1

3 Answers 3

3

Yes it is possible to serialize an anonymous type. The easiest way that comes to mind is to create a wrapper object which implements ISerializable and uses reflection to inspect an anonymous type for it's fields and serialize them as appropriate. It would be very ugly but would work.

However I think the more important question is

Is it possible to deserialize an anonymous type?

The answer to that is "Not in a general sense". Anonymous types are assembly specific types. So while it's possible to do in a specific manner for a specific anonymous type, it is not doable in the general sense and not between different assemblies since they are internal.

1
  • It is not that complicated to do. Some reflection magic will do the trick. Take a look at my solution: martinnormark.com/…
    – MartinHN
    Feb 5, 2011 at 8:33
1

Define "serialize." Serialization implies the ability to deserialize later, and if there is no defined class, there would be nothing to deserialize to. However, if you simply want the data to be placed in an XML file for retreival later, you could certainly do that.

Create an instance of your XML Document of choice (XmlDocument, XDocumnet, whatever) and build it that way (inserting your nodes and values as you go), then use basic File IO to save it somewhere. Or, if you're just trying to pass it between processes or somesuch, pass it as a MemoryStream or Byte[]

0

Only in a very general sense, in that there is nothing to stop you creating XML that represents an object and nothing to stop you creating an object whose state reflects some XML.

In the specific sense of directly supported by the framework, and resulting in an object of a type defined by an assembly, then no. By definition, an anonymous object isn't defined, that's what makes it anonymous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.