Search code examples
jsonserializationsilverlight-4.0datacontractdatacontractjsonserializer

Silverlight 4 DataContractJsonSerializer, private fields of a derived class


I use DataContractJsonSerializer to deserialize json data in Silverlight 4. Json data key names do not match my class property names; so I guess I have to use DataMemberAttribute. So I did the following:

[DataContract]
public class Person : Model
{
    [DataMember(Name = "id")]
    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

    [DataMember(Name = "name")]
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

Now deserialization fails because I didn't apply DataContractAttribute to Person's base class Model. Is it a strict requirement? Also, after I applied DataContractAttribute to Model, deserialization fails again, because I applied DataMember attributes to private fields, not to the public properties. Why can't I apply them to private members (the documentation seems to say otherwise).

NOTE: server-side code is not ASP.NET; so WCF isn't used.


Solution

  • In order to get the private members to serialize over WCF correctly, we had to change them all to protected internal instead of private. Maybe the same applies for DataContractJsonSerializer?