WCF: DeSerialize string datamember as int
I really can't figure this one out! (if it's even possible). From a WCF service we are receiving product information. A product datacontract has some members that are defined as strings (but are actually integers), but we want to process them as integers.
When I change the datatype in the contract on the client side from string to int, my problem is solved. However, some products have a string.Empty value, which can't be deserialized into an int. Is there anyway around this? Really don't want to con开发者_Python百科vert my resultset after deserialization...
Well, since those DataContract classes you get are always partial classes, you could just simply add a second partial class, and provide "PropertyAsInt" properties.
Something like this:
public partial class Product
{
public int ProductNumberAsInt
{
get
{
if(!string.IsNullOrEmpty(ProductNumber))
{
int result = -1;
if(int.TryParse(ProductNumber, out result)
return result;
else
return -1;
}
return 0;
}
}
}
So you would just simply define a ProductNumberAsInt
property, which would inspect the underlying string property called ProductNumber
. If it's null
or string.Empty
, just return a default value, e.g. -1 or 0 or whatever works for you.
If it's not null/empty, you can try to convert it to an Int, and if successful, return that int - otherwise return another indicator (again, take your pick, -1, 0, whatever makes sense for you).
That way, you don't have to mess with the WCF data contracts, no messy manual hacking, and you can tweak those extra properties as you need them.
Marc
精彩评论