473,854 Members | 1,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom serialization object type in C# throws exception


I'm having problem serialization an object instance which contains a public property on the object type
My object hierarchy is many levels deep, so for simplicty I created to following which produces the same error

Let's say there is a class called ParkingSpot with a public member Vehicle having an object type of object
For simplicity, let's say that Vehicle could be anything, hence I create a new object of Car typ
and assign it to the Vehicle property of the ParkingSpot object

When I try to serialize the ParkingSpot class, I get an error with an inner exception stating
_innerException : {"The type SerializationTe st.Car was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

My classes are the following

using System
using System.Runtime. Serialization
using System.Xml.Seri alization

public class ParkingSpot : ISerializable

private object _vehicle
public ParkingSpot(){

[XmlElement("Veh icle")
public object Vehicl


return _vehicle


_vehicle = value
#region ISerializable Member
public void GetObjectData(S erializationInf o info, StreamingContex t context

// TODO: Add ParkingSpot.Get ObjectData implementatio

public class Ca

public string Make
public string Model
public Car(){

I have a button on a form with the following serialization code

private void btnSerialize_Cl ick(object sender, System.EventArg s e

ParkingSpot parkingSpot = new ParkingSpot()
Car car = new Car()
car.Make = "Nissan"
car.Model = "Maxima"
parkingSpot.Veh icle = car;


// Serializatio
XmlSerializer s = new XmlSerializer(t ypeof(ParkingSp ot))
TextWriter w = new StreamWriter(@" C:\ParkingSpot. xml")
s.Serialize(w, parkingSpot)

catch (Exception exp

Console.WriteLi ne ("{0}",exp.Mess age);

Does anyone know what the problem is
I tried changing the [XmlElement] attribute to [XmlAnyElement] attribute, but this causes another error

Please help, I've been stumped on this one for over a day

Thanks a lot
Nov 16 '05 #1
1 2646
1)You don't need to implement ISerializable or use the [Serializable]
attribute for XML serialization. ISerializable and the Serializable
attribute are for full-fidelity runtime serialization. XML serialization is
for the most part concerned with an object's public shape.

2) Doesn't Car need to be a subclass of Vehicle in your example?

3) [XmlElement] and [XmlAnyElement] won't help.

4) When you XML {serialize|dese rialize} objects with polymorphic fields, you
must take steps to ensure that the serializer is aware of the additional
types that might be present. Given:

public class ParkingSpot
public Vehicle;


class Vehicle {...}
class Car: Vehicle {...}

One approach is to add an XmlInclude attribute to the Vehicle base class,
like this:
[XmlInclude(type of(Car))]
public class Vehicle

Alternatively, you can attribute the ParkingSpot class:
[XmlInclude(type of(Car))]
public class ParkingSpot { }

Another method is to pass an array of additional types to the serializer
when it's constructed, like so:
XmlSerializer s = new XmlSerializer(t ypeof(ParkingSp ot),
new Type[] {typeof(Car)});

Mickey Williams
Author, "Microsoft Visual C# .NET Core Reference", MS Press

Nov 16 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Craig Schneider | last post by:
// Is there any way to override the XML Serialization of the following SimpleClass // to turn off the DefaultValue of a boolean? Sure, I can override the DefaultValue from // true to false, but that is not what I want/need. I really need to just override the fact // that the developer ever supplied a DefaultValue. Setting an override DefaultValue of null // or "new object()" errors. Any help would be appreciated.
by: Opa | last post by:
Hi I'm having problem serialization an object instance which contains a public property on the object type My object hierarchy is many levels deep, so for simplicty I created to following which produces the same error Let's say there is a class called ParkingSpot with a public member Vehicle having an object type of object For simplicity, let's say that Vehicle could be anything, hence I create a new object of Car typ and assign it to...
by: AnkitAsDeveloper [Ankit] | last post by:
Hi i am serializing a 'ref struct' object as follows : private: void Seri( String ^path, Object^ obj ) { FileStream^ fileStrm ; try { //Serialize entire object into Binary stream
by: Knecke | last post by:
Hi all. I have a problem with returning a custom Result object with webservice. The classes i use is described below (some fields and properties is removed) public class Result { int statusCode;
by: AMDRIT | last post by:
Hello everyone, I have created a custom component and one of its properties is a class object with it's own properties. During runtime, I can assign values to the class object properties just fine. However, when attempting to assing default values as designtime in the propertygrid, nothing is working on the class object. I know that I am doing it wrong, any ideas what it is? Thanks in advance
by: leodippolito | last post by:
Dear sirs, I am using custom wrappers to primitive types in my classes, so I can have some flags when working with the database ("undefined" and "null") .. So instead of: public class User
by: Zachary Turner | last post by:
Hello, I have a situation where I would like to perform custom serialization and deserialization of an existing .NET framework object (specifically, System.DateTime). Is there a common paradigm here, for how I can override the default behavior of DateTime serialization and provide my own? I want to use this custom serialized DateTime in many places, and don't want to provide custom serialization routines for every single object that...
by: ThunderMusic | last post by:
Hi, I have a custom form that works fine when I debug it or run it in release mode but cannot be loaded in the designer... Actually, it can be loaded in the designer when no control is on it, but the resizing tool (in the designer) is offset both horizontally and vertically and when I put a control on it, as soon as I save, the designer throws an exception (but cannot be reproduced everytime) and the form cannot be loaded anymore unless...
by: JosAH | last post by:
Introduction Upon hearing the word, "Serialization", the first question which comes to mind is ... "What is Serialization?" We know that we can create resusable objects in Java. But the lifetime of those objects lasts only as long as the Java virtual machine is running. Once we close the JVM, we lose all those objects. What if someone wants objects to be available after JVM restarts? This is where Serialization comes into play. ...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.