反序列化JSON会生成默认类

时间:2014-02-18 13:17:40

标签: c# windows-phone-8 json.net

我正在使用此代码反序列化对象

PlayerData = JsonConvert.DeserializeObject<UserData>(response.Content);

我的UserData类如下

    public class UserData : BindableBase
    {
        public string UID { get; set; }
        public string UDID { get; set; }
        public object liveID { get; set; }
        public int timeLastSeen { get; set; }
        public string country { get; set; }
        public string username { get; set; }
        public string session { get; set; }
        public int serverTime { get; set; }
        public int PremiumCurrency { get; set; }

        public UserData()
        {

        }
    }

当它反序列化时,我得到一个返回的对象,好像我刚刚调用new UserData()但是如果从类定义中删除: BindableBase,它会正确地反序列化。我想这是因为基类包含一些不在JSON中的属性,但我只想要那些被忽略的属性。有这个设置吗?

BindableBase类如下

[Windows.Foundation.Metadata.WebHostHidden]
[DataContract]
public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (object.Equals(storage, value)) return false;

        storage = value;
        this.OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

JSON如下

{
    "UID": "4",
    "UDID": "",
    "liveID": null,
    "timeLastSeen": 1392730436,
    "country": "GB",
    "username": "User4",
    "PremiumCurrency": "20",
    "session": "5c8583311732fa816e333dc5e6426d65",
    "serverTime": 1392730437
}

1 个答案:

答案 0 :(得分:1)

很明显,回答问题出在基类的DataContract属性中。修复它的简单方法是使用DataMember属性修饰派生类的属性。