设一个类似的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 });
因此,此代码将删除所有空值。如果在一个嵌套对象中填充了任何值,我如何获得null值。例如,如果
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;
}
希望这对每个人都有帮助。