C#在Json序列化中動(dòng)態(tài)忽略某些屬性或字段
C#在Json序列化中動(dòng)態(tài)忽略某些屬性或字段
先準(zhǔn)備好Newtonsoft.Json的程序包。
固定忽略:
在代碼上面加上[JsonIgnore]特性。
動(dòng)態(tài)忽略:
使用鮮為人知的ShouldSerialize方法。
ShouldSerialize的用法:
在需要序列化的類當(dāng)中增加一個(gè)bool類型的方法,
方法的名字為ShouldSerialize和你需要序列化的字段的名字相加,
且沒(méi)有參數(shù)。
如果方法返回true,則該字段會(huì)被序列化。
如果方法返回false,則該字段不會(huì)被序列化。
如果字段擁有對(duì)應(yīng)的ShouldSerialize方法,則會(huì)被序列化,
如果字段打上了[JsonIgnore]特性,則以特性優(yōu)先,不會(huì)再觸發(fā)ShouldSerialize方法。
以下示例代碼一共有9個(gè)字段或?qū)傩詀,b,c,d,e,f,g,h,s:
然后給出調(diào)用方式:
執(zhí)行結(jié)果:
{"a":1,"c":"3","e":true,"h":null}
解釋:
我們一共寫了a-g的7個(gè)ShouldSerialize方法,名字的前綴都為ShouldSerialize,后綴分別為a-g的字段名字。
字段b和s上打了固定的忽略特性,不會(huì)被序列化。
字段a,b,c,e上的ShouldSerialize的返回結(jié)果為true,會(huì)被序列化,但是b字段打了固定忽略,所以b不會(huì)被序列化。
字段h,沒(méi)有打上固定忽略特性,也沒(méi)有對(duì)應(yīng)的ShouldSerialize方法,默認(rèn)會(huì)被序列化。
TestClase test = new TestClase(); string s = JsonConvert.SerializeObject(test);
public class TestClase { public int a = 1; [JsonIgnore] public int b = 2; public string c = "3"; public string d = "4"; public bool e = true; public bool f = false; public string g { get; set; } public string h { get; set; } [JsonIgnore]//固定忽略字段s,這個(gè)字段不會(huì)被序列化 public string s = "a,b,c,e"; //方法的名字為ShouldSerialize + a public bool ShouldSerializea() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x)=>x == "a").Count > 0) { return true; } else { return false; } } //方法的名字為ShouldSerialize + b public bool ShouldSerializeb() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x) => x == "b").Count > 0) { return true; } else { return false; } } //方法的名字為ShouldSerialize + c public bool ShouldSerializec() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x) => x == "c").Count > 0) { return true; } else { return false; } } public bool ShouldSerialized() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x) => x == "d").Count > 0) { return true; } else { return false; } } public bool ShouldSerializee() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x) => x == "e").Count > 0) { return true; } else { return false; } } public bool ShouldSerializef() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x) => x == "f").Count > 0) { return true; } else { return false; } } public bool ShouldSerializeg() { List<string> strs = s.Split(',').ToList<string>(); if (strs.FindAll((x) => x == "g").Count > 0) { return true; } else { return false; } } }

浙公網(wǎng)安備 33010602011771號(hào)