反序列化的对象的所有值都设置为Null

aah*_*ens 4 c# json json.net deserialization c#-4.0

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

JSON范例

{
"Keys": [
    {
        "RegistrationKey": "asdfasdfa",
        "ValidationStatus": "Valid",
        "ValidationDescription": null,
        "Properties": [
            {
                "Key": "Guid",
                "Value": "i0asd23165323sdfs68661358"
            }
        ]
    }
 ]
}
Run Code Online (Sandbox Code Playgroud)

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

Keys myDeserializedObjValid = (Keys)JsonConvert.DeserializeObject(strResponseValid, typeof(Keys));
validationStatusValid = myDeserializedObjValid.ValidationStatus;
Run Code Online (Sandbox Code Playgroud)

这是我的课

    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; }
    }
Run Code Online (Sandbox Code Playgroud)

Fra*_*ank 7

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

    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);
 }
Run Code Online (Sandbox Code Playgroud)


Ima*_*idi 5

就我而言,这是因为我的目标类型为这些属性设置了内部(或私有)设置修饰符。

public class Summary{

     public Class2 Prop1 { get; internal set; }
     public Class1 prop2 { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

删除内部修饰符后,json.net也像序列化步骤一样反序列化那些对象

  • 除了删除内部修饰符之外,还可以添加 [JsonProperty]-属性:/sf/answers/2756659111/ (4认同)