我正在使用这段代码反序列化一个对象
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
}
最佳答案
很明显可以回答问题出在基类的 DataContract
属性中。修复它的简单方法是使用 DataMember
属性装饰派生类的属性。
关于c# - 反序列化 JSON 会生成默认类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855044/