JsonConvert.DeserializeObject将属性留空

时间:2019-03-31 23:48:02

标签: c# json.net

TLDR:如果反序列化对象的所有字段都为null,没有任何例外,请检查您的基类是否具有[DataContract]属性,这使Json.net忽略没有[DataMember]的每个属性。

对不起,代码量很大,但我无法缩小导致问题的原因。

我有这个json对象,它具有类AssetViewModel的数组

import random

x = input("Rolar dado? Insira : S/N")

while x == "s":
        print("Nº dado:", random.randrange(1,7))
        x = input("Rolar dado? Insira : S/N")
else:
    break

AssetViewModel:

[{
    "id":117,
    "name":"BMP",
    "creator":null,
    "extension":".bmp",
    "creationDate":"2019-03-31T23:18:20.8080488Z",
    "modificationDate":"2019-03-31T23:18:21.3191844Z",
    "size":1440056,
    "isDeleted":false,
    "version":0,
    "hasSinglePreview":true,
    "hasCollagePreview":false,
    "customPreviews":0,
    "group":null,
    "collection":null,
    "project":null,
    "tags":[]
}]

如果我将其反序列化,请参见下文,它工作正常。

public class AssetViewModel : IAsset
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IUser Creator { get; set; }
    public string Extension { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime ModificationDate { get; set; }
    public long Size { get; set; }
    public bool IsDeleted { get; set; }
    public int Version { get; set; }
    public bool HasSinglePreview { get; set; }
    public bool HasCollagePreview { get; set; }
    public int CustomPreviews { get; set; }
    public IGroup Group { get; set; }
    public ICollection Collection { get; set; }
    public IProject Project { get; set; }
    public ICollection<ITag> Tags { get; set; }
}

但是对于AssetViewModel2类却不是:

var result = JsonConvert.DeserializeObject<IEnumerable<AssetViewModel>>(content);

属性是相同的,除了在此类中,它们具有带有NotifyOfPropertyChange()的后备字段以用于WPF绑定。我将其中一些更改为具体类型,因为我认为这可能会引起一些麻烦,但这并没有帮助。

如果使用AssetViewModel2反序列化,则结果的所有属性均保持为空,并且没有任何异常。

在AssetViewModel2中我怎么了?

2 个答案:

答案 0 :(得分:1)

你全都错了

例如

"creator":{

已映射到

Creator { get; set; }
  • 要么更正您的类和属性的大小写。
  • 或者使用[JsonProperty(PropertyName = "FooBar")]正确地映射它们

答案 1 :(得分:0)

问题出在基类。我正在使用caliburn micros PropertyChangedBase。该类具有[DataContract]属性,因此有必要将[DataMember]属性添加到应反序列化的属性中。

解决方案:

  • 复制不具有[DataContract]属性的类,并将[JsonIgnore]添加到IsNotifying或
  • 将[DataMember]属性添加到应反序列化的每个属性中。
相关问题