473,785 Members | 2,421 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom serialization object type in C# throws exception

Opa
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 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

ge

return _vehicle

se

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

// TODO: Add ParkingSpot.Get ObjectData implementatio

#endregio
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;

tr

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

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 2641
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;
}

and:

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
www.neudesic.com
www.servergeek.com/blogs/mickey

Nov 16 '05 #2

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

Similar topics

0
4002
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.
1
2866
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...
3
2069
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
1
7274
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;
2
2446
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
1
1591
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
3
2643
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...
4
5834
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...
0
4712
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. ...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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,...
0
10325
Oralloy
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...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
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...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
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...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2879
bsmnconsultancy
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.