all groups > dotnet xml > february 2005 >
You're in the

dotnet xml

group:

Deserialization issues, handling integer properties correctly?


Deserialization issues, handling integer properties correctly? Raterus
2/25/2005 10:13:04 AM
dotnet xml:
Hello,

I'm running into an issue when I'm deserializing an xml file into my =
custom object. This issues revolve around integer properties (though =
I'm sure others would apply). I have to account for my xml response to =
be empty (<myintegerfield />), if I simply use one property, I get =
errors that my "Input field not in correct format" when I deserialize. =
I've come up with a fix, but I'm not sure if it is the best path. =
Basically I'm defining two properties, one that the XmlSerializer uses, =
and one that I actually interface from with external code. Here it =
is:

Private m_grossincome as Integer

'This property is just used for serialization/deserialization, =
it could just as well be private (if the xmlserializer would parse it =
that is)
<XmlElement(ElementName:=3D"GROSSINCOME")> _
Public Property GI() As String
Get
Return CStr(Me.m_grossincome)
End Get
Set(ByVal Value As String)
If Value Is Nothing OrElse Not IsNumeric(Value) Then
Me.m_grossincome =3D 0
Else
Me.m_grossincome =3D CInt(Value)
End If
End Set
End Property

'This is the property I use from external code
<XmlIgnore()> _
Public Property GrossIncome() As Integer
Get
Return Me.m_grossincome
End Get
Set(ByVal Value As Integer)
Me.m_grossincome =3D Value
End Set
End Property

It works great, but I'm wondering if there is an easier way to go about =
this.

Thanks for any help,
Re: Deserialization issues, handling integer properties correctly? Derek Harmon
2/26/2005 10:31:42 PM
[quoted text, click to view]

Yes, an InvalidOperationException stating the "Input field not in correct format,"
because it's incompatible with the Int32 type of your property. Essentially, an
empty tag says your property should be Nothing or an Empty String (it doesn't
know if you think that means 0 or -999 or Int32.MaxInt), and Value Types
(integers, doubles, decimals, booleans, dates) aren't allowed to be Nothing
in .NET and may have no meaningful conversion from String.Empty.

The manner in which you've dealt with it, by having serialization go to a String
property that's a surrogate, and marking a real API property with XmlIgnore,
is the usual way people go about it.

: :
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsable.Never)> _
[quoted text, click to view]
: :

One additional suggestion I can make is that you can mark the serialization-
only property with EditorBrowsableAttribute of Never to prevent it from
showing up in IntelliSense even though it's public. At least this prevents it
from "polluting" your IntelliSense.


Derek Harmon

AddThis Social Bookmark Button