强制Json.net反序列化中的构造函数参数值

时间:2015-04-19 15:20:15

标签: c# json.net json-deserialization

是否可以强制Json.net传递构造函数参数的默认值?

我尝试使用自定义ContractResolver来覆盖CreateConstructorParametersCreatePropertyFromConstructorParameter方法,并将返回的JsonProperty.DefaultValue属性设置为我想要的值和DefaultValueHandling属性到DefaultValueHandling.Populate

通过覆盖CreateObjectContract方法,我可以看到匹配的CreatorParametersProperties都包含我的默认值。但是,我仍然会将null值传递给构造函数。

我甚至尝试将属性上的Converter设置为只返回所需默认值的转换器,但仍然没有运气。

以下是ConstractResolver代码:

public class DataControllerContractResolver : DefaultContractResolver
{
    ///The desired default value
    private readonly IDataController _dataController;

    private readonly Type _dataControllerType;
    private readonly JsonConverter<IDataController> _converter;

    public DataControllerContractResolver(IDataController dataController)
    {
        _dataController = dataController;
        _dataControllerType = dataController.GetType();
        _converter = SimpleJsonConverter<IDataController>.From((reader, controller, arg3) => _dataController, (writer, controller, arg3) => {});
    }

    protected override IList<JsonProperty> CreateConstructorParameters(ConstructorInfo constructor, JsonPropertyCollection memberProperties)
    {
        var props = base.CreateConstructorParameters(constructor, memberProperties);

        foreach (var prop in memberProperties.Where(p => p.PropertyType.IsAssignableFrom(_dataControllerType)).ToList())
        {
            prop.DefaultValue = _dataController;
            prop.Converter = _converter;
            prop.DefaultValueHandling = DefaultValueHandling.Populate;
            prop.Ignored = false;
        }

        foreach (var prop in props.Where(p => p.PropertyType.IsAssignableFrom(_dataControllerType)).ToList())
        {
            prop.DefaultValue = _dataController;
            prop.Converter = _converter;
            prop.DefaultValueHandling = DefaultValueHandling.Populate;
            prop.Ignored = false;
        }


        return props;
    }

    protected override JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo)
    {
        var prop = base.CreatePropertyFromConstructorParameter(matchingMemberProperty, parameterInfo);

        if (prop.PropertyType.IsAssignableFrom(_dataControllerType))
        {
            prop.DefaultValue = _dataController;
            prop.Converter = _converter;
            prop.MemberConverter = _converter;
            prop.DefaultValueHandling = DefaultValueHandling.Populate;
            prop.Ignored = false;
        }

        return prop;
    }

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var contract = base.CreateObjectContract(objectType);
        return contract;
    }
}

2 个答案:

答案 0 :(得分:1)

如果我覆盖property.DefaultValue中的property.DefaultValueHandlingCreateProperties(Type type, MemberSerialization memberSerialization),我可以完成这项工作。我没有你的所有课程(没有IDataController),所以这里有一个简单的例子:

public class DefaultStringValueContractResolver : DefaultContractResolver
{
    public string DefaultStringValue { get; set; }

    public DefaultStringValueContractResolver(string defaultStringValue)
    {
        this.DefaultStringValue = defaultStringValue;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);
        // Set all string properties to have a default value of "this is a default value"
        foreach (var property in properties.Where(p => p.PropertyType == typeof(string)))
        {
            property.DefaultValue = DefaultStringValue;
            property.DefaultValueHandling = DefaultValueHandling.Populate;
        }
        return properties;
    }
}

然后:

public class TestClass
{
    const string DefaultStringValue = "This is a default string value";

    public string Property1 { get; set; }

    public string Property2 { get; set; }

    public static void Test()
    {
        var settings = new JsonSerializerSettings { ContractResolver = new DefaultStringValueContractResolver(DefaultStringValue) };
        var test = JsonConvert.DeserializeObject<TestClass>("{}", settings);
        Debug.Assert(test.Property1 == DefaultStringValue && test.Property2 == DefaultStringValue); // No assert
        Debug.WriteLine(JsonConvert.SerializeObject(test)); // Prints {"Property1":"This is a default string value","Property2":"This is a default string value"}
    }
}

需要注意的一点是:如果默认值是引用类型,则包含该属性的类的所有实例都将具有引用相同默认值实例的默认值。

答案 1 :(得分:1)

在找不到此问题的内置解决方案之后,我向下弯曲并在Github上添加了默认值检查和pull-request。 JamesNK(Json.net创建者)implemented the solution略有不同,但它在最新版本中可用。