如果有一个对象,Json.Net倾向于在对象上使用默认的(无参数)构造函数。如果存在多个构造函数,并且您希望Json.Net使用非默认
[JsonConstructor]构造函数,则可以将属性添加到希望Json.Net调用的构造函数中。
[JsonConstructor]public Result(int? pre, 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? pre = (int?)jo["Code"]; string format = (string)jo["Format"]; // Construct the Result object using the non-default constructor Result result = new Result(pre, 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);



