反序列化对象的所有值都设置为 Null [英] Deserialized Object Has All Values Set to Null

查看:18
本文介绍了反序列化对象的所有值都设置为 Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 JSON 反序列化为自定义对象,但我的所有属性都设置为 null 并且不确定发生了什么.有人看错了吗?

I'm trying to deserialize JSON into a custom object but all my properties are set to null and not sure what's going on. Does anyone see anything wrong?

JSON 示例

{
"Keys": [
    {
        "RegistrationKey": "asdfasdfa",
        "ValidationStatus": "Valid",
        "ValidationDescription": null,
        "Properties": [
            {
                "Key": "Guid",
                "Value": "i0asd23165323sdfs68661358"
            }
        ]
    }
 ]
}

这是我的代码,其中 strResponseValid 是上面的 JSON.

Here is my Code, where strResponseValid is the JSON above.

Keys myDeserializedObjValid = (Keys)JsonConvert.DeserializeObject(strResponseValid, typeof(Keys));
validationStatusValid = myDeserializedObjValid.ValidationStatus;

这是我的课程

    public class Keys
    {
        public string RegistrationKey { get; set; }
        public string ValidationStatus { get; set; }
        public string ValidationDescription { get; set; }
        public List<Properties> PropertiesList { get; set; }
    }

    public class Properties
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }

推荐答案

您的 JSON 有一个外部对象,其中包含一组 Key 对象.以下代码有效(我测试过):

Your JSON has an outer object which contains a collection of Key objects. The following code works (I tested it):

    class KeyWrapper
    {
        public List<Key> Keys { get; set; }
    }

    class Key
    {
        public string RegistrationKey { get; set; }
        public string ValidationStatus { get; set; }
        public string ValidationDescription { get; set; }
        public List<Properties> Properties { get; set; }
    }

    public class Properties
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }

    public void DeserializeKeys()
    {            
        const string json = @"{""Keys"": 
            [
                {
                    ""RegistrationKey"": ""asdfasdfa"",
                    ""ValidationStatus"": ""Valid"",
                    ""ValidationDescription"": null,
                    ""Properties"": [
                        {
                            ""Key"": ""Guid"",
                            ""Value"": ""i0asd23165323sdfs68661358""
                        }
                    ]
                 }
             ]
         }";

        var keysWrapper = Newtonsoft.Json.JsonConvert.DeserializeObject<KeyWrapper>(json);
 }

这篇关于反序列化对象的所有值都设置为 Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆