I have the following C # code example that is automatically generated from xsd using the svcutils.exe application.
[DataContract] public enum Foo { [EnumMember(Value = "bar")] Bar = 1, [EnumMember(Value = "baz")] Baz = 2 } [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; } }
The following is an example unit test that attempts to deserialize a sample JSON document into a UNameIt class.
[TestClass] public class JsonSerializer_Fixture { public const string JsonData = @"{ ""id"":123456, ""name"":""John Doe"", ""foo"":""Bar""}"; [TestMethod] public void DataObjectSimpleParseTest() { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UNameIt)); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData)); UNameIt dataObject = serializer.ReadObject(ms) as UNameIt; Assert.IsNotNull(dataObject); Assert.AreEqual(123456, dataObject.Id); Assert.AreEqual(Foo.Baz, dataObject.Foo); } }
Unfortunately, the test does not provide the following reason:
System.Runtime.Serialization.SerializationException: failed to deserialize an object of type MyNamespace.Units.UNameIt. The value "Bar" cannot be parsed as type "Int64".
The test will pass if I update the JSON string to replace the string specifier for Enum with an integer, for example.
public const string JsonData = @"{ ""id"":123456, ""name"":""John Doe"", ""foo"":""1""}";
I don't have the flexibility to change the supplied JSON, so I have to figure out how to convert the representation of the Enum string, possibly to serialization. Ideally, I would like to facilitate this without changing my auto-generation class, because as soon as I create the class again, I will lose my changes.
I am wondering if it is possible to extend the DataContractJsonSerializer to custom Enumerations descriptors? Or maybe there is a better way to do this?
json c # wcf xsd datacontractserializer
user989046
source share