Newtonsoft json DeserializeObject with DefaultValueHandling 不适用于运行时对象

Newtonsoft json DeserializeObject with DefaultValueHandling not working with runtime object

我正在尝试将一个对象的 属性 设置为 return 一个默认值,而在我反序列化的 json 中没有那个 属性。

我读到我可以使用 [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] 属性实现此目的。

    public class MyClass {
        public readonly string Id;
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public RectangleF Position { get; set; } = new RectangleF(0, 0, 1, 1);

        [JsonConstructor]
        public MyClass(string id, RectangleF position) {
            Id = id;
            Position = position;
        }
    }

    [Test]
    public void DeserializeDefaultValue() {
        var json = JObject.FromObject(new { id = "123" });
        var obj = json.ToObject<MyClass>();
        Expect(obj.Position, Is.EqualTo(new RectangleF(0, 0, 1, 1)));
    }

测试失败,位置总是returning new RectangleF(0, 0, 0, 0)

我不能有 [DefaultValue] 属性,就像我在很多示例中看​​到的那样,因为 RectangleF 在运行时被初始化。

我尝试了很多方法,例如在构造函数中使用 [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)],用位置的默认值重载构造函数,但没有任何效果。

我缺少一些简单的东西来实现这个目标吗?

所以我稍微修改了你正在做的事情,但这适用于你想要完成的事情。

public class MyClass
{
    public readonly string Id;
    public RectangleF Position { get; set; }

    [JsonConstructor]
    public MyClass(string id, RectangleF? position)
    {
        Id = id;
        Position = position ?? new RectangleF(0, 0, 1, 1);
    }
}

补充一下,如果您拥有的唯一承包商将任何值分配给 属性,属性 初始值设定项将被忽略(始终)。如果您添加一个默认构造函数(没有参数),那么我相信您上面的内容将始终有效。