昨天,我需要在 JSON 文件中添加一个属性,我已使用 DefaultHandling
完成此操作,如 this previous question 中所述:
[JsonProperty("DIAGNOSTICS",DefaultvalueHandling = DefaultvalueHandling.Populate)]
public bool DIAGNOSTICS { get; set; }
现在我正在处理一个更复杂的情况:
摘自我的源代码:
[JsonProperty("NAME")]
public string NAME { get; set; }
[JsonProperty("i1.ENABLE")]
public bool i1ENABLE { get; set; }
[JsonProperty("i2.ENABLE")]
public bool i2ENABLE { get; set; }
[JsonProperty("i3ENABLE")]
public bool i3ENABLE { get; set; }
...
所需的 JSON 结果:
"NAME": "i1","i1.ENABLE": false,/* i2.ENABLE and i3.ENABLE are not shown */
...
"NAME": "i2","i2.ENABLE": false,/* i1.ENABLE and i3.ENABLE are not shown */
...
"NAME": "i3","i3.ENABLE": false,/* i1.ENABLE and i2.ENABLE are not shown */
...
所以我的问题是,这是否可能(伪代码),如果是,如何?
[JsonProperty("i1.ENABLE",DefaultvalueHandling = (IF(NAME=="i1") THEN DefaultvalueHandling.Populate))]
public bool i1ENABLE { get; set; }
[JsonProperty("i2.ENABLE",DefaultvalueHandling = (IF(NAME=="i2") THEN DefaultvalueHandling.Populate))]
public bool i2ENABLE { get; set; }
[JsonProperty("i3.ENABLE",DefaultvalueHandling = (IF(NAME=="i3") THEN DefaultvalueHandling.Populate))]
public bool i3ENABLE { get; set; }
编辑(在 Laurent 的第一个回答之后)
我的序列化代码如下:
JsonSerializerSettings js = new JsonSerializerSettings();
js.DefaultvalueHandling = DefaultvalueHandling.Ignore;
string temp = JsonConvert.SerializeObject(root,Formatting.Indented,js);
万一在属性声明中做不到,可以在这里做吗?