Json.Net 更喜欢在对象上使用默认(无参数)构造函数(如果有的话)。如果有多个构造函数并且您希望 Json.Net 使用非默认构造函数,那么您可以添加[JsonConstructor]
属性到您希望 Json.Net 调用的构造函数。
[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
...
}
构造函数参数名称必须与 JSON 对象的相应属性名称匹配(忽略大小写),这样才能正常工作。但是,您不必为对象的每个属性都提供构造函数参数。对于那些构造函数参数未涵盖的 JSON 对象属性,Json.Net 将尝试使用公共属性访问器(或标记为的属性/字段)[JsonProperty]
) 在构造对象后填充该对象。
如果您不想向类添加属性或者不以其他方式控制您尝试反序列化的类的源代码,那么另一种选择是创建一个自定义Json转换器实例化并填充您的对象。例如:
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);