JsonConvert.DeserializeObject<List<ConclusionEntityCategory>> is returning null objects in List

本秂侑毒 提交于 2020-12-27 03:08:55

问题


I am new to Json.Net and am having a difficult time deserializing my Json objects into .Net objects. It creates ConclusionEntityCategory objects but those in turn contain null objects. My code is as follows:

const string catAndSubCat = @"[
    {
        ""Category"": ""risk factor"",
        ""SubCategory2"": [
            ""default"",""Minor risk factor"",""Major risk factor""
        ]
    },
    {
        ""Category"": ""intervention group"",
        ""SubCategory2"": [
            ""default"",""Minor risk factor"",""Major risk factor""
        ]
    }
]";

var c = JsonConvert.DeserializeObject<List<ConclusionEntityCategory>>(catAndSubCat);

Here is my class:

internal class ConclusionEntityCategory
{
    internal string Category { get; set; }
    internal string SubCategory1 { get; set; }
    internal List<string> SubCategory2 { get; set; }
}

The value of c is a List<ConclusionEntityCategory> with 2 ConclusionEntityCategory objects in the List. However, all of the properties within each of the ConclusionEntityCategory objects are null.

Any help with this problem would be greatly appreciate.


回答1:


As a result of Category, SubCategory1, and SubCategory2 being internal, the serializer cannot set them. These need to be public properties in order to be populated.

internal class ConclusionEntityCategory
{
 public string Category { get; set; }
 public string SubCategory1 { get; set; }
 public List<string> SubCategory2 { get; set; }
}



回答2:


Try marking the internal properties on ConclusionEntityCategory with [JsonProperty] attribute, or if that is not desirable, set DefaultContractResolver.DefaultMemberSearchFlags to include non-public flag.



来源:https://stackoverflow.com/questions/23523316/jsonconvert-deserializeobjectlistconclusionentitycategory-is-returning-null

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