views:

562

answers:

2

I'm trying to consume a RESTful web service using WCF. I have no control over the format of the web service, so I have to make a few workarounds here and there. One major problem I cannot seem to get around, however, is how to make WCF deserialize an enum as a string.

This is my code (names changed, obviously):

[DataContract]
public enum Foo
{
    [EnumMember( Value = "bar" )]
    Bar,

    [EnumMember( Value = "baz" )]
    Baz
}

[DataContract]
public class UNameIt
{
    [DataMember( Name = "id" )]
    public long Id { get; private set; }

    [DataMember( Name = "name" )]
    public string Name { get; private set; }

    [DataMember( Name = "foo" )]
    public Foo Foo { get; private set; }
}

And this is the returned data that fails deserialization:

{
     "id":123456,
     "name":"John Doe",
     "foo":"bar"
}

Finally, the exception thrown:

There was an error deserializing the object of type Service.Foo. The value 'bar' cannot be parsed as the type 'Int64'.

I do not want to switch to using the XmlSerializer, because, among its many other shortcomings, it won't let me have private setters on properties.

How do I make WCF (or, well, the DataContractSerializer) treat my enum as string values?

EDIT: Doing this seems to be impossible, and the behavior is the way it is by design. Thank you Microsoft, for not giving us options, having to resort to hacks. Doing it the way somori suggests seems to be the only way to get string enums with JSON and WCF.

A: 

Er..? Aren't enums integer? The exception is valid. I dunno if this helps: http://msdn.microsoft.com/en-us/library/aa347875.aspx

kurtnelle
No, it's not. Have you read that article yourself? Here's an interesting excerpt:Generally the data contract includes enumeration member names, not numerical values. However, when using the data contract model, if the receiving side is a WCF client, the exported schema preserves the numerical values.The problem is, I'm being a WCF client. However, the server uses string enums. I'm a little stumped...
Alex
Could the server code be buggy? Is it possible to use data structure in this instance?
kurtnelle
The server is not a WCF service, I think it runs Python. I can't change the way they do things, I'm just a consumer in this scenario, and I have to go by their rules.
Alex
+1  A: 

This might be a silly question.

What happens if you do

[DataMember( Name = "foo" )]
private string foo { get; private set; }

public Foo Foo 
{ 
  get 
  {
    return Foo.Parse(foo);
  }
}

?

somori
I've tried that already, and that works, but it's a hack, and if it can be avoided, I want to avoid it.
Alex
Actually, this seems to be the only way to do it, see http://stackoverflow.com/questions/794838/datacontractjsonserializer-and-enums/794962#794962
Alex