How to configure JSON enumeration deserialization in .NET?

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?

+8
json c # wcf xsd datacontractserializer
source share
2 answers

This is design behavior. Here is a quote from Enumerations and a JSON paragraph on MSDN :

The values ​​of enumeration elements are considered as numbers in JSON, which is different from how they are processed in data contracts, where they are included as participant names.

In addition, the DataContractJsonSerializer will automatically serialize all enumerations, so EnumMemberAttribute is actually ignored.

For a workaround , check out this answer on SO .

+6
source share

This is the job:

 var ret = new JavaScriptSerializer().Deserialize<tblGridProjects>(retApi.Item2); 

But you cannot use datamembers attributes, therefore you cannot rename properties. You must set the property name as Json sended.

0
source share

All Articles