JSON.NET C#中的反序列化导致空对象

我正在尝试使用JSON.NET反序列化来填充C#对象(ImportedProductCodesContainer)和数据。

ImportedProductCodesContainer.cs:

using Newtonsoft.Json; [JsonObject(MemberSerialization.OptOut)] public class ImportedProductCodesContainer { public ImportedProductCodesContainer() { } [JsonProperty] public ActionType Action { get; set; } [JsonProperty] public string ProductListRaw { get; set; } public enum ActionType {Append=1, Replace}; } 

JSON字符串:

 {"ImportedProductCodesContainer":{"ProductListRaw":"1 23","Action":"Append"}} 

C#代码:

  var serializer = new JsonSerializer(); var importedProductCodesContainer = JsonConvert.DeserializeObject(argument); 

问题是importProductCodesContainer在运行上面的代码后仍然为空(Action = 0,ProductListRaw = null)。 你能帮我弄清楚出了什么问题吗?

您有一个太多级别的ImportedProductCodesContainer 。 它正在创建一个新的ImportedProductCodesContainer对象(来自模板化反序列化器),然后尝试在其上设置一个名为ImportedProductCodesContainer的属性(来自JSON的顶层),该属性将是包含其他两个值的结构。 如果仅对内部部件进行反序列化

 {"ProductListRaw":"1 23","Action":"Append"} 

然后你应该得到你期望的对象,或者你可以创建一个带有ImportedProductCodesContainer属性的新结构

 [JsonObject(MemberSerialization.OptOut)] public class ImportedProductCodesContainerWrapper { [JsonProperty] public ImportedProductCodesContainer ImportedProductCodesContainer { get; set; } } 

并使用该模板设置您的反序列化器,然后您的原始JSON应该可以工作。

也可以使用该JSON库使用其他属性/标志来更改此行为,但我不太清楚它。