Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wcf deserialize enum as string

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.

like image 614
Alex Avatar asked Jan 22 '10 22:01

Alex


2 Answers

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);
  }
}

?

like image 160
Simon Gill Avatar answered Nov 08 '22 22:11

Simon Gill


I know this is an old post, but I think it worth mentioning.

I received a similar error where the deserialization of the json string failed, seeming to deserialize to the wrong types.

The fix for me was to simply URL encode the json string before sending it to the server. A simple but easy mistake to make.

HttpUtility.UrlEncode(JSONInstruction) /*remember to encode the string*/
like image 44
MHALottering Avatar answered Nov 08 '22 22:11

MHALottering