1

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
synergetic
  • 7,756
  • 8
  • 65
  • 106

1 Answers1

1

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?

competent_tech
  • 44,465
  • 11
  • 90
  • 113
  • Should I also apply InternalsVisibleTo attribute to my assembly? – synergetic Nov 19 '11 at 02:48
  • Absolutely; forgot about that little gem. – competent_tech Nov 19 '11 at 03:17
  • How about (not) applying DataContract attribute to base classes? Is it all or nothing kind of thing? – synergetic Nov 19 '11 at 03:25
  • To be honest, I've never tried it that way, we always apply it all the way down the chain. What errors were you getting or was it just not serializing? – competent_tech Nov 19 '11 at 03:27
  • Something like: "Type '**' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute...". So I guess I have to apply all the way down, but so far I haven't found any such a statement online. Also, I found out SerializableAttribute isn't available in Silverlight. – synergetic Nov 19 '11 at 03:40
  • No it isn't. The way we got around that and reused our existing code without having to add compiler defs everywhere was create a dummy serializableattribute in the silverlight project. Just inherit from attribute and you should be good to go. – competent_tech Nov 19 '11 at 03:48