JSON.NET Deserialization in C# results in empty object

不羁岁月 提交于 2019-12-08 19:46:09

问题


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 importedProductCodesContainer remains empty after running the code above (Action = 0, ProductListRaw = null). Can you please help me figure out what's wrong?


回答1:


You have one too many levels of ImportedProductCodesContainer. It's creating a new ImportedProductCodesContainer object (from the templated deserializer) and then attempting to set a property on it called ImportedProductCodesContainer (from the top level of your JSON) which would be a structure containing the other two values. If you deserialize the inner part only

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

then you should get the object you're expecting, or you can create a new struct with an ImportedProductCodesContainer property

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

and template your deserializer with that then your original JSON should work.

It may also be possible to change this behaviour using other attributes / flags with that JSON library but I don't know it well enough to say.



来源:https://stackoverflow.com/questions/2972431/json-net-deserialization-in-c-sharp-results-in-empty-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!