how to serialize a generic field object

  • Thread starter Thread starter Pascal
  • Start date Start date
P

Pascal

Hi everybody.
I have to serialize to XML a class like this:

public class MyClass{
string myString;
object myObject;
}

myObject can be a number(int, float, double), a date or a string. Any
suggestion?
 
Hi,

where is the problem?

XmlSerializer will serialize your object property as <MyObject
xsi:type="xsd:int">12</MyObject> or
<MyObject xsi:type="xsd:string">teststring</MyObject>

You should provide public properties and a default constructor
 
Hi,

where is the problem?

XmlSerializer will serialize your object property as <MyObject
xsi:type="xsd:int">12</MyObject> or
<MyObject xsi:type="xsd:string">teststring</MyObject>

You should provide public properties and a default constructor

I tried but I receive an "Error reflecting type MyClass" exception.
This is what I wrote:

public class MyClass
{
[XmlAttribute("Description")]
public string description;
[XmlAttribute("Value")]
public object Value;
}

If I write

public class MyClass
{
[XmlAttribute("Description")]
public string description;
[XmlAttribute("Value")]
public int Value;
}
It works.
 
[Serializable()]
public class MyClass
{
private string _Description;
private object _Value;

public MyClass() {}

public string Description
{
get { return _Description; }
set { _Description = value; }
}

public string Value
{
get { return _Value; }
set { _Value = value; }
}
}
 
[Serializable()]
public class MyClass
{
private string _Description;
private object _Value;

public MyClass() {}

public string Description
{
get { return _Description; }
set { _Description = value; }
}

public string Value
{
get { return _Value; }
set { _Value = value; }
}


I don't think the problem can be solved using properties. As i said if
i specify the type of every fields it works. Of course I used the
attribute [Serializable], I 've just forgotten to write it in the
example.


[Serilizable]
public class MyClass
{
[XmlAttribute("Description")]
public string description;
[XmlAttribute("Value")]
public object Value;
}
 
Hmm ok,

i see. The problem is the XmlAttribute which can only be applied to
simple types not to complex types like object.
Use XmlElement.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top