JSON.NET Deserialization in C # results in an empty object

I am trying to populate a C # object (ImportedProductCodesContainer) with data using JSON.NET deserialization.

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 string:

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

C # code:

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

The problem is that importProductCodesContainer remains empty after running the above code (Action = 0, ProductListRaw = null). Could you help me figure out what is wrong?

+6
source share
1 answer

You have too many levels of ImportedProductCodesContainer . It creates a new ImportedProductCodesContainer object (from a templated deserializer), and then tries to set a property on it called ImportedProductCodesContainer (from the top level of your JSON), which will be a structure containing two other values. If you deserialize only the inside

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

then you should get the expected object or create a new structure with the ImportedProductCodesContainer property

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

and create your deserializer so that your working JSON works.

It is also possible to change this behavior using other attributes / flags with this JSON library, but I don't know what is good enough to say.

+1
source share

All Articles