newTonJson 如何在枚举中使用构造函数重载

http://www.voidcn.com/article/p-foffrlfj-bso.html

Json.Net喜欢在一个对象上使用默认(无参)构造函数。如果有多个构造函数,并且您希望Json.Net使用非默认构造函数,那么可以将[JsonConstructor]属性添加到要让Json.Net调用的构造函数中。

[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
    ...
}

重要的是,构造函数参数名称与JSON对象的相应属性名称匹配,以使此正确工作。但是,您不必为对象的每个属性都具有构造函数参数。对于没有被构造函数参数覆盖的那些JSON对象属性,Json.Net将尝试使用公共属性访问器(或标记有[JsonProperty]的属性/字段)在构造对象之后填充该对象。

如果不想向类中添加属性或者不控制要尝试反序列化的类的源代码,那么另一种替代方法是创建自定义JsonConverter来实例化和填充对象。例如:

class ResultConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Result));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON for the Result into a JObject
        JObject jo = JObject.Load(reader);

        // Read the properties which will be used as constructor parameters
        int? code = (int?)jo["Code"];
        string format = (string)jo["Format"];

        // Construct the Result object using the non-default constructor
        Result result = new Result(code, format);

        // (If anything else needs to be populated on the result object, do that here)

        // Return the result
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后,将转换器添加到您的序列化程序设置,并使用反序列化时的设置:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);
//当然了 上面是答者写的
实际上有传递JsonConverter集合的重载 可以直径
Result result = JsonConvert.DeserializeObject<Result>(jsontext,new ResultConverter());
原文地址:https://www.cnblogs.com/hurui1/p/14138587.html