Serialize JSON object as per the condition using C# and Json.NET

后端 未结 1 1711
庸人自扰
庸人自扰 2021-01-17 05:25

I am serializing data from a database into JSON format using JSON.Net. But I am not able to get the result I expect.

I have to create JSON objects according to cert

1条回答
  •  野的像风
    2021-01-17 06:03

    The [JsonExtensionData] attribute causes the key-value pairs in the marked dictionary to be serialized as if they were properties of the class containing the dictionary. This attribute is handled specially by Json.Net and thus the IgnoreEmptyEnumerablesResolver suggested by @Alex in the comments will not have an effect on it. But you could restructure your classes such that you don't need the attribute for datamapKey and datamapKey1, and that would allow the resolver to work on those dictionaries when they are empty, giving you the output you want.

    public class DatamapItem
    {
        [JsonExtensionData]
        public Dictionary DatamapItemFields { get; set; } = new Dictionary();
        public Dictionary datamapKey { get; set; } = new Dictionary();
        public Dictionary datamapKey1 { get; set; } = new Dictionary();
    }
    
    public class RootObject
    {
        public List datamapItems { get; set; }
    }
    

    Demo fiddle: https://dotnetfiddle.net/Gw03gY


    If you don't like that idea or don't want to modify your class structure, another option is to load your object instance into a JObject and use a recursive method to remove empty tokens from the hierarchy. This approach is covered in detail in How to omit/ignore/skip empty object literals in the produced JSON?.

    Here is a demo fiddle showing that approach with your existing class structure: https://dotnetfiddle.net/jmNgYi

    0 讨论(0)
提交回复
热议问题