.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

DataContractJsonSerializer serialization of EnumMember

Posted By:      Posted Date: September 02, 2010    Points: 0   Category :WCF
I discovered the other day that the DataContractJsonSerializer ignores the [EnumMember] attribute.  If it encounters a enum value it will always use the integer value of the enum.  For example if I define the following data contracts... [DataContract] public enum VehicleType { [EnumMember(Value = "Car")] Car, [EnumMember(Value = "Bike")] Bike } [DataContract] public class MyDataContract { public VehicleType Vehicle { get; set; } } ... and return a MyDataContract with Vehicle set to VehicleType.Bike it will be serialised in Json as 1.  If I use the standard Xml serialiser it will be serialised to my specified value of 'Bike'. This is specified in this MSDN article as the intended behaviour, but it seems a bit strange to me and a little bit frustrating.  I could probably spend time writing my own serialiser to do this, but it seems like a feature that should be there in the framework.   Is there a good reason why this serialiser ignores the [EnumMember] attributes?  If not could this be changed in a future release? Thanks IainBlog Twitter Please "mark as answer" if this answers the question.. thanks!

View Complete Post

More Related Resource Links

Service Station: Serialization in Windows Communication Foundation


Windows Communication Foundation supports several serialization mechanisms and provides a simple, interoperable foundation for future service-oriented applications. Here Aaron Skonnard explains it all.

Aaron Skonnard

MSDN Magazine August 2006

Class To Contract: Enrich Your XML Serialization With Schema Providers In The .NET Framework


The Microsoft .NET Framework 1.x provided minimal options for mapping classes to schemas and serializing objects to XML documents, making this sort of mapping quite a challenge. The .NET Framework 2.0 changes all this with Schema providers and the IXmlSerializable interface.

Keith Pijanowski

MSDN Magazine June 2006

Advanced Serialization: Format Your Way to Success with the .NET Framework Versions 1.1 and 2.0


While .NET offers adequate support for the simple serialization cases, issues arise when you're attempting to support delegates and subscribers, versioning, and class hierarchies. . In addition, the introduction of generics in The .NET Framework breaks new ground in the complexity of the serialization task and the power of serialization tools. This article discusses these issues and related pitfalls, suggests techniques and workarounds that address them, and recommends when and how to best use the new serialization abilities.

Juval Lowy

MSDN Magazine October 2004

Cutting Edge: Binary Serialization of DataSets


The ADO. NET DataSet object plays an essential role in most of today's distributed, multitiered applications. Instances of the DataSet class are used to move data across the tiers and to exchange data with external services.

Dino Esposito

MSDN Magazine October 2004

Cutting Edge: Binary Serialization of ADO.NET Objects


One of the key elements that makes ADO. NET superior to ADO is the level of integration with XML. In ADO, XML is just an I/O format. In addition, the ADO XML format is totally inflexible and doesn't allow any type of customization.

Dino Esposito

MSDN Magazine December 2002

.NET Column: Run-time Serialization, Part 3


This is the third part of my three-part series on serialization. In part one, I showed how to serialize and deserialize objects. I also showed how to define types that allow instances of themselves to be serialized.

Jeffrey Richter

MSDN Magazine September 2002

Is this an example of binary serialization


Hi , I have write this code for write error message in .txt file and this code is working fine.

void writeToLogFile(string logMessage)


        string strLogMessage = string.Empty;

        string strLogFile = System.Configuration.ConfigurationManager.AppSettings["logFilePath"].ToString();

        StreamWriter swLog;

        strLogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);

        if (!File.Exists(strLogFile))


            swLog = new StreamWriter(strLogFile);




            swLog = File.AppendText(strLogFile);






I want to know is this an example of binary serialization? 
If YES then please inform me from which line the serialization is done? 
If NO then please tell me an example of Binary Serialization ?

XML Serialization & List


 Hi all,


I'm working on the following code :


[System.Runtime.Serialization.DataContractAttribute(Name = "SalesOrder")]
    public partial class SalesOrder

        private List<OrderLine> orderLineField;


public SalesOrder()
            this.orderLineField = new List<OrderLine>();
            this.orderHeaderField = new OrderHeader();

        public List<OrderLine> OrderLine
                return this.orderLineFi

Bug? : Sgen breaks web-service serialization

I am using the noaa weather web service and it works fine if I have not run sgen on the assembly. I have sgen disabled in the project settings and instead run it explicitly in the main build. I run sgen using the command: sgen /a:myassembly.dll /force /compiler:/keyfile:myassembly.snkThis creates an [assembly_name].XmlSerializers.dll and when running the application again, the same call to the web-service fails with the following exception. This is internal to the web-service code so I'm stuck for what to do other than not run sgen:System.InvalidOperationException: There was an error generating the XML document. ---> System.ArgumentException: Item has already been added. Key in dictionary: 'myassembly.gov.weather.www.productType' Key being added: 'myassembly.gov.weather.www.productType' at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add) at System.Collections.Hashtable.Add(Object key, Object value) at System.Xml.Serialization.XmlSerializationWriter.AddWriteCallback(Type type, String typeName, String typeNs, XmlSerializationWriteCallback callback) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.InitCallbacks() at System.Xml.Serialization.XmlSerializationWriter.GetTypeEntry(Type t) at System.Xml.Serialization.XmlSerializationWriter.WriteReferencedElement(String name, String ns, Object o, Type ambientType)

Can this be down with serialization?

Let's say I serialize a List<Double>... Can I then deserialize just a "portion" of the serialized List?  If I need to access a range of Doubles in the List, do I have to deserialize the entire list and then access the items I need? I know this is a somewhat strange concept, but it's a real-world requirement. At present, I'm serializing each item in the List using Bitconverter.GetBytes, and storing the 8 bytes into an aggregated byte array which I write to a file. That way, I can later seek into the file, read a range of bytes and then use BitConverter.ToDouble to get the original double values. But using BitConverter.GetBytes on each item in a list of 1,000,000 doubles (resulting in an 8,000,000 byte array) is fairly sluggish (over 1/2 second on 2GHz Core 2 Duo). I suspect it would be faster to serialize the entire List<Doubles> all-at-once rather than item at a time.  But do I then give up the ability to "index" into the stored serialized Doubes if I serialize the List rather than the items in the List?   If I have to deserialize the entire List before I can access individual items in that List, then I'll have to stick with how I'm doing it now... or perhaps find a way to speed-up BitConverter.GetBytes (would this perhaps lend itself to using Parallel.For and allo

Serialization Samples in .Net

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Xml.Serialization; using System.IO; namespace Serialization_Sample {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("Enter the Member Details");             GetDetails();             Console.WriteLine("Binary Serialization Completed.....");             Console.WriteLine("Binary Deserialization Started.....");             ReadDetails();             Console.WriteLine("Binary Deserialization Completed...");             Console.ReadLine();             SoapGetDetails();         &nbs

Serialization and generics : problem with xmlinclude

Hello everyone. I've got a hierarchy of class like this: [Serializable] [xmlinclude(DiscreteDomain)] public abstract class Domain { } [Serializable] [xmlinclude(DiscreteDomain<>)] public abstract class DiscreteDomain : Domain { } [Serializable] public sealed class DiscreteDomain<T> : DiscreteDomain { } I can't serialize an object of type DiscreteDomain<T> because xmlinclude can't be used with a generics like DiscreteDomain<> (a type must be specified but i can't).   How can I serialize this type of object ?   Thx, JP

Serialization error in a for each loop

I have a for each loop in a 3.5 workflow. This takes a list if criteria to build a query string to call a Secure Webservive necesitating the use of a certificate. I load the certificate further up stream and pass it as a dependency property. The process returns a serialization error for the certificate. How do I avoid this error?  Thanks!

DataContractJsonSerializer: Problem when deserializing the Date

Sorry for cross-posting. I posted the same question on the Silverlight forum, but it has not received a single answer yet. The majority of folks there must be more interested in UI than in more fundamental stuff.     Hello everyone! Let's say we have the folllowing POCO classes: public class PocoObject : List<PocoPropertyData> {     public PocoObject() {}     public override string ToString()     {         var parts = new List<string>();         foreach (var pd in this)             parts.Add(string.Format("{{N=[{0}], Type=[{1}], V=[{2}]}}", pd.N, pd.V == null ? typeof(object) : pd.V.GetType(),  pd.V));         return string.Join(",", parts);     } } public class PocoPropertyData {     public string N { get; set; }  // the property name     public object V { get; set; }  // the property value } As you can see, the PocoPropertyData can hold value of any type. When I execute the following code in both .NET 4 application and Silverlight 4 application: ========================================================= var poco = new PocoObject {       { new PocoPropertyData { N = "DateTimeField", V =  Da
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend