c# - 反序列化 JSON 会生成默认类

标签 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
}

最佳答案

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

关于c# - 反序列化 JSON 会生成默认类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855044/

相关文章:

c# - SCardEstablishContext 内存泄漏

c# - 应用程序域刷新/重启

c# - Windows Phone 8.1 应用构建中缺少 WMAppManifest.xml

c# - 无法在 C# 中将类型 'System.EventHandler' 隐式转换为 'System.Windows.RoutedEventHandler'

android - 插入移动操作系统核心应用程序

c# - nHibernate 转 Json

c# - 使用反射确定事件是否是静态的

c# - 我将如何使用 System.DirectoryServices.Protocol 验证用户名/密码?

javascript - C# JSON 字符串到 JavaScript 数组

c# - 忽略序列化为 JSON 时抛出异常的类成员