Note that there are some explanatory texts on larger screens.

plurals
  1. POwcf deserialize enum as string
    primarykey
    data
    text
    <p>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.</p> <p>This is my code (names changed, obviously):</p> <pre><code>[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; } } </code></pre> <p>And this is the returned data that fails deserialization:</p> <pre><code>{ "id":123456, "name":"John Doe", "foo":"bar" } </code></pre> <p>Finally, the exception thrown:</p> <blockquote> <p>There was an error deserializing the object of type Service.Foo. The value 'bar' cannot be parsed as the type 'Int64'.</p> </blockquote> <p>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.</p> <p>How do I make WCF (or, well, the DataContractSerializer) treat my enum as string values?</p> <p><strong>EDIT</strong>: 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload