Tom Squires
Tom Squires

Reputation: 9286

Deserialize null

I have a WCF REST webservice and have datacontracts with several string properties. I want to be able accept null values (as below) however setting the property to a nullable string (string?) in the contract gives a compiler error. When i leave the datacontract properties as strings it errors when the client sends me xml like below. The error it gives is a serialisation errror. Is what im trying to do possible?

<myclass>
<somestring xsi:nil="true" />
<myclass>

Upvotes: 0

Views: 671

Answers (2)

Connell
Connell

Reputation: 14411

  • A string doesn't have to be delcared as nullable as it is a reference type not a value type and therefore can be null anyway. string str = null; compiles just fine.

  • That's not valid XML, however that could cause a runtime error (not compile time)

Try this

<myclass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <somestring xsi:nil="true" />
</myclass>

Upvotes: 2

Jonathan Dickinson
Jonathan Dickinson

Reputation: 9218

You might try omitting the element or the attribute (I can't remember if WCF will accept this):

<myclass>
</myclass>

The main problem is you have not defined the xsi namespace. Assuming that myclass is the root of your document:

<myclass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <somestring xsi:nil="true" />
</myclass>

Remember that xml (http://www.w3.org/XML/1998/namespace) and xmlns (http://www.w3.org/2000/xmlns/) are the only namespaces and prefixes provided by XML by default.

You could also use XmlSerializerFormatAttribute and use the old System.Xml.Serialization implementation - which does recognise http://www.w3.org/2001/XMLSchema-instance.

Further Information

  • I assume you made a typo with your XML example - just keep in mind that your closing tag is incorrect.
  • String cannot be used in Nullable<T> because it is not a value type - you can assign Null to it because it is a reference type. Use String in your DataContract.

Upvotes: 0

Related Questions