如果只有所有数据成员为空,如何在C#中序列化为Json时删除空值

如果只有所有数据成员为空,如何在C#中序列化为Json时删除空值,c#,json,json.net,C#,Json,Json.net,让我们有一个C类的 class A { public string p; public string q; } class B { public string c; public string d; } class C { public A a; public B b; } 我正在用代码序列化它 string json =

让我们有一个C类的

    class A
    {
        public string p;
        public string q;
    }

    class B
    {
        public string c;
        public string d;
    }

    class C
    {
        public A a;
        public B b;
    }

我正在用代码序列化它

string json = JsonConvert.SerializeObject(JsonObject,
                            new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
因此,此代码将删除所有空值。如果在一个嵌套对象中填充了任何值,如何获取空值。 例如,如果

A.p = null,  
A.q = "filled",
B.c = "filled",
B.d = "filled"
因此json字符串应该是

{
  "A": {
    "p": null,
    "q": "filled"
  },
  "B": {
    "c": "filled",
    "d": "filled" 
  } 
}
但如果物体是这样的

A.p = null,  
A.q = null,
B.c = "filled",
B.d = "filled"
Json字符串应该是

{
  "B": {
    "c": "filled",
    "d": "filled" 
  } 
}

我不知道这是否是最好的解决方案,但这是我解决了这个问题

//Serialize the object to json, if false then removes the null properties else ignore them
private static string Serialize(C JsonObject, bool ignoreNullProperties)
{
    return JsonConvert.SerializeObject(JsonObject,
             new JsonSerializerSettings { NullValueHandling = ignoreNullProperties == true ? NullValueHandling.Ignore : NullValueHandling.Include, Formatting = Formatting.Indented });
}

        
public static string SerializePerservingNullValuesForNonEmptyClass(C JsonObject)
{
    string notHavingNullValues = Serialize(C, true);// serialized to get json with no null properties
    string havingNullValues = Serialize(C, false);// serialized to json with null properties
    //converted both Json string to dictionary<string,object>
    Dictionary<string, object> notHavingNullValuesDictionary = 
       JsonConvert.DeserializeObject<Dictionary<string, object>>(notHavingNullValues);
    Dictionary<string, object> havingNullValuesDictionary = 
       JsonConvert.DeserializeObject<Dictionary<string, object>>(havingNullValues);

    Dictionary<string, object> resultDictionary = 
    GetNullValuesForObjectHavingAnyNonNullValues(havingNullValuesDictionary, 
    notHavingNullValuesDictionary);

    return Serialize(resultDictionary, false);
}

//iterated through dictionary having no null value and taking values from dictionary having all values and stored them to a new dictionary
private static Dictionary<string, object> GetNullValuesForObjectHavingAnyNonNullValues(Dictionary<string, object> havingNull, Dictionary<string, object> notHavingNull)
{
   Dictionary<string, object> expectedJsonFormat = new Dictionary<string, object>();
   foreach (KeyValuePair<string, object> values in notHavingNull)
   {
      expectedJsonFormat.Add(values.Key, havingNull[values.Key]);
   }
   return expectedJsonFormat;
}
//将对象序列化为json,如果为false,则删除null属性,否则忽略它们
私有静态字符串序列化(C JsonObject、bool ignoreNullProperties)
{
返回JsonConvert.SerializeObject(JsonObject,
新JsonSerializerSettings{NullValueHandling=ignoreNullProperties==true?NullValueHandling.Ignore:NullValueHandling.Include,Formatting=Formatting.Indented});
}
公共静态字符串序列化PerservingNullValuesForOnemptyClass(C JsonObject)
{
string notHavingNullValues=Serialize(C,true);//序列化以获取不带null属性的json
字符串havingNullValues=Serialize(C,false);//序列化为具有null属性的json
//将两个Json字符串都转换为字典
Dictionary notHavingNullValuesDictionary=
JsonConvert.DeserializeObject(NothavingNullValue);
具有NullValuesDictionary=
JsonConvert.DeserializeObject(具有NullValue);
字典结果字典=
GetNullValuesProjectHavingAnyNonNullValues(havingNullValuesDictionary,
不包含空值(数字);
返回序列化(resultDictionary,false);
}
//在没有空值的字典中迭代,并从具有所有值的字典中获取值,然后将它们存储到新字典中
私有静态字典GetNullValuesProjectHavingAnyNonNullValues(字典havingNull,字典notHavingNull)
{
Dictionary expectedJsonFormat=新字典();
foreach(notHavingNull中的KeyValuePair值)
{
expectedJsonFormat.Add(values.Key,havingNull[values.Key]);
}
返回expectedJsonFormat;
}

希望这对大家都有帮助。

我可能错了,但我认为最好的办法是在序列化之前添加一些逻辑。如果对象的所有属性都为null,则不要序列化它。据我所知,如果所有属性都为空,Newtonsoft无法排除整个对象。您的示例与您的描述不匹配。任何值都不应该读取任何属性吗?对于类
a
B
,您可以使用自定义的
JsonConverter
执行此类操作,但在序列化数据之前,可能更容易过滤/转换数据。如果我的问题不够清楚,请原谅。我已经找到了解决这个问题的办法。