简体   繁体   English

使用C#和Json.NET按照条件序列化JSON对象

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

I am serializing data from a database into JSON format using JSON.Net. 我使用JSON.Net将数据库中的数据序列化为JSON格式。 But I am not able to get the result I expect. 但我无法得到我期望的结果。

I have to create JSON objects according to certain conditions like if my data for datamap is null then it should not be included in the JSON, and if it is not null then it should be included. 我必须根据某些条件创建JSON对象,例如,如果我的datamap数据为null,那么它不应该包含在JSON中,如果它不为null,则应该包含它。

public class DatamapKey
{
    [JsonExtensionData]
    public Dictionary<string, JToken> DatamapKeyFields = new Dictionary<string, JToken>();
}
public class DatamapKey1
{
    [JsonExtensionData]
    public Dictionary<string, JToken> DatamapKey1Fields = new Dictionary<string, JToken>();
}
public class DatamapItem
{
    [JsonExtensionData]
    public Dictionary<string, JToken> DatamapItemFields = new Dictionary<string, JToken>();
    public DatamapKey datamapKey { get; set; }
    public DatamapKey1 datamapKey1 { get; set; }
}
public class RootObject
{
    public List<DatamapItem> datamapItems { get; set; }
}

Output JSON: 输出JSON:

{
  "datamapItems": [
    {
      "datamapKey": {
        "module": 1,
        "id": 1391
      },
      "datamapKey1": {},
      "paramName": "VE8321C",
      "min": "0",
      "max": "40"
    },
    {
      "datamapKey": {},
      "datamapKey1": {},
      "paramName": "VE8321C",
      "min": "0",
      "max": "40"
    },
    {
      "datamapKey": {
        "module": 1,
        "id": 1391
      },
      "datamapKey1": {
        "module": 1,
        "id": 1391
      },
      "paramName": "VE8321C",
      "min": "0",
      "max": "40"
    }
  ]
}

Expected Output: 预期产出:

{
  "datamapItems": [
    {
      "paramName": "VE8321C",
      "datamapKey": {
        "module": 1,
        "id": 1391
      },
      "min": "0",
      "max": "40"
    },
    {
      "paramName": "VE8321C",
      "min": "0",
      "max": "40"
    },
    {
      "paramName": "VE8321C",
      "datamapKey": {
        "module": 1,
        "id": 1391
      },
      "datamapKey1": {
        "module": 1,
        "id": 1391
      },
      "min": "0",
      "max": "40"
    }
  ]
}

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. [JsonExtensionData]属性使标记字典中的键值对序列化,就好像它们是包含字典的类的属性一样。 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. 此属性由Json.Net专门处理,因此IgnoreEmptyEnumerablesResolver在评论中建议的IgnoreEmptyEnumerablesResolver不会对其产生影响。 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. 但是你可以重构你的类,这样你就不需要datamapKeydatamapKey1的属性了,这样就可以让解析器在它们为空时处理那些字典,为你提供所需的输出。

public class DatamapItem
{
    [JsonExtensionData]
    public Dictionary<string, JToken> DatamapItemFields { get; set; } = new Dictionary<string, JToken>();
    public Dictionary<string, JToken> datamapKey { get; set; } = new Dictionary<string, JToken>();
    public Dictionary<string, JToken> datamapKey1 { get; set; } = new Dictionary<string, JToken>();
}

public class RootObject
{
    public List<DatamapItem> datamapItems { get; set; }
}

Demo fiddle: https://dotnetfiddle.net/Gw03gY 演示小提琴: 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. 如果您不喜欢这个想法或者不想修改类结构,另一个选择是将对象实例加载到JObject并使用递归方法从层次结构中删除空标记。 This approach is covered in detail in How to omit/ignore/skip empty object literals in the produced JSON? 如何省略/忽略/跳过生成的JSON中的空对象文字中详细介绍了这种方法 .

Here is a demo fiddle showing that approach with your existing class structure: https://dotnetfiddle.net/jmNgYi 这是一个演示小提琴,显示了您现有的类结构的方法: https//dotnetfiddle.net/jmNgYi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM