DataContractSerializer does not properly deserialize, values for methods in object are missing

sachin  picture sachin · Oct 30, 2009 · Viewed 7.8k times · Source

My SomeClass

[Serializable]
[DataContract(Namespace = "")]
public class SomeClass
{
    [DataMember]
    public string FirstName
    { 
        get; set;
    }

    [DataMember]
    public string LastName
    { 
        get; set;
    }

    [DataMember]
    private IDictionary<long, string> customValues;
    public IDictionary<long, string> CustomValues
    {
        get { return customValues; }
        set { customValues = value; }
    }
}

My XML File:

<?xml version="1.0" encoding="UTF-8"?>
 <SomeClass>
 <FirstName>John</FirstName>
 <LastName>Smith</LastName>
 <CustomValues>
    <Value1>One</Value1>
    <Value2>Two</Value2>
 </CustomValues >
 </SomeClass>

But my problem is for the class, i am only getting some of the data for my methods when i deserialize.

var xmlRoot = XElement.Load(new StreamReader(
                    filterContext.HttpContext.Request.InputStream,
                    filterContext.HttpContext.Request.ContentEncoding));
XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(xmlRoot.CreateReader());
 DataContractSerializer ser = new DataContractSerializer(typeof(SomeClass));
//Deserialize the data and read it from the instance.
SomeClass someClass = (SomeClass)ser.ReadObject(reader, true);

So when I check "someClass", FirstName will have the value john, But the LastName will be null.

Mystery is how can i get some of the data and not all of the data for the class. So DataContractSerializer is not pulling up all the data from xml when deserializing.

Am i doing something wrong.

Any help is appreciated. Thanks in advance.

Let me know if anyone has the same problem or any one has solution

Answer

sachin  picture sachin · Oct 30, 2009

Well i found my own answering after playing it a lot around....it has to be in an alpahbetical order. so if class has

[Serializable]
[DataContract(Namespace = "")]    
public class SomeClass
{
    [DataMember]
    public string FirstName
    { 
        get; set;
    }

    [DataMember]
    public string LastName
    { 
        get; set;
    }

    [DataMember]
    private IDictionary<long, string> customValues;
    public IDictionary<long, string> CustomValues
    {
        get { return customValues; }
        set { customValues = value; }
    }
}

then xml should be define alphabetically.

<?xml version="1.0" encoding="UTF-8"?>
 <SomeClass>
 <CustomValues>
    <Value1>One</Value1>
    <Value2>Two</Value2>
 </CustomValues >
 <FirstName>John</FirstName>
 <LastName>Smith</LastName>
 </SomeClass>

well why the h... it has to be in alphabetical?