我正在使用此代码反序列化对象
PlayerData = JsonConvert.DeserializeObject<UserData>(response.Content);
我的用户数据类如下所示
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
}
很明显,问题出在基类DataContract
属性上。 修复它的简单方法是使用 DataMember
属性修饰派生类的属性。