WCF反序列化枚举作为字符串字符串、序列化、WCF

由网友(顾一辞)分享简介:我试图消耗使用WCF一个RESTful Web服务。我有过Web服务的格式无法控制,所以我要在这里和那里做一些变通。一个主要的问题,我似乎无法得到解决,但是,如何使WCF反序列化的枚举作为一个字符串。I'm trying to consume a RESTful web service using WCF. I ha...

我试图消耗使用WCF一个RESTful Web服务。我有过Web服务的格式无法控制,所以我要在这里和那里做一些变通。一个主要的问题,我似乎无法得到解决,但是,如何使WCF反序列化的枚举作为一个字符串。

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.

这是我的code(名称变了,很明显):

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:

有一个错误反序列化类型Service.Foo的对象。值'酒吧'不能被解析为类型的Int64。

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

我不想要切换到使用XmlSerializer,因为除它的诸多缺点,它不会让我有私人制定者的属性。

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.

我如何让WCF(或,好了,DataContractSerializer的)把我的枚举的字符串值?

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

修改:这样做似乎是不可能的,其行为是它是设计的方式。谢谢微软,不给我们选择,不必诉诸黑客。这样做的somori方式建议似乎得到字符串枚举使用JSON和WCF的唯一途径。

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.

推荐答案

这可能是一个愚蠢的问题。

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

阅读全文

相关推荐

最新文章