我有一个具有默认构造函数的类,也是一个带有一组参数的重载构造函数.这些参数与对象上的字段匹配,并在构造时分配.此时我需要默认构造函数用于其他目的,所以我想保留它,如果可以的话.
我的问题:如果我删除默认构造函数并传入JSON字符串,该对象将正确反序列化并传入构造函数参数而不会出现任何问题.我最终以我期望的方式取回填充的对象.但是,只要我将默认构造函数添加到对象中,当我调用JsonConvert.DeserializeObject<Result>(jsontext)属性时就不再填充了.
此时我尝试添加new JsonSerializerSettings(){CheckAdditionalContent = true}反序列化调用.那什么都没做.
另一个说明.除了参数以小写字母开头之外,构造函数参数确实与字段的名称完全匹配.我不认为这很重要因为,就像我提到的,反序列化工作正常,没有默认构造函数.
这是我的构造函数的示例:
public Result() { }
public Result(int? code, string format, Dictionary<string, string> details = null)
{
Code = code ?? ERROR_CODE;
Format = format;
if (details == null)
Details = new Dictionary<string, string>();
else
Details = details;
}
Run Code Online (Sandbox Code Playgroud) 我绝对记得在某个地方看到一个使用反射或其他东西这样做的例子.这与SqlParameterCollection用户无法创造的事情有关(如果我没有记错的话).不幸的是再也找不到了.
有人可以在这里分享这个技巧吗?并不是说我认为它是一种有效的开发方法,我只是对这样做的可能性非常感兴趣.
我试图了解如何JsonConvert.DeserializeObject<X>(someJsonString)使用构造函数设置值.
using Newtonsoft.json
public class X {
[JsonProperty("some_Property")]
public string SomeProperty {get;}
[JsonProperty("some_Property_2")]
public string SomeProperty2 {get;}
public X(string someProperty, string someProperty2) {
SomeProperty = someProperty;
SomeProperty2 = someProperty2;
}
public static X parseObject(string parseThisJson) {
JsonConvert.DeserializeObject<X>(someJsonString);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我想了解JsonConvert.DeserializeObject如何能够正确地反序列化它.json序列化是否使用此public X(string someProperty, string someProperty2)构造函数?如果是这样,如何调用和使用此构造函数?
会发生什么是parseThisJson除了some_Property和some_Property_2之外还有更多的键值对?
使用特定的.ctor via JsonConstructor进行反序列化IList<ISomeInterface>属性时,参数名称必须与原始 Json名称匹配,并且JsonProperty不使用这些属性上的映射.
SpokenLanguages参数始终为null,因为它不匹配spoken_languages,但JsonProperty它有一个映射:
public partial class AClass : ISomeBase
{
public AClass() { }
[JsonConstructor]
public AClass(IList<SysType> SysTypes, IList<ProductionCountry> production_countries, IList<SpokenLanguage> SpokenLanguages)
{
this.Genres = SysTypes?.ToList<IGenre>();
this.ProductionCountries = production_countries?.ToList<IProductionCountry>();
this.SpokenLanguages = SpokenLanguages?.ToList<ISpokenLanguage>();
}
public int Id { get; set; }
public IList<IGenre> Genres { get; set; }
[JsonProperty("production_countries")]
public IList<IProductionCountry> ProductionCountries { get; set; }
[JsonProperty("spoken_languages")]
public IList<ISpokenLanguage> SpokenLanguages { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这只是Json.Net …