【问题标题】:Transform a JsonProperty in another Type based on the Property value根据 Property 值将 JsonProperty 转换为另一种类型
【发布时间】:2019-07-17 14:36:39
【问题描述】:

我在我的对象中定义了这个 JsonProperty 以序列化为 JSON:

[JsonProperty(PropertyName = "client_state")]
public Boolean IsRunning { get; set; }

我想要实现的是转换 JSON“client_state”,以便当 IsRunning 属性为 true 时 JSON 属性将是一个包含文本“isrunning”的字符串,当 IsRunning 属性为“notrunning”时将是一个字符串错误的。 在 JSON 序列化过程中如何定义这种转换?

【问题讨论】:

标签: c# .net json


【解决方案1】:

您可以添加一个中间属性来执行序列化并忽略原始属性

[JsonProperty(PropertyName = "client_state")]
public string ClientState => IsRunning ? "isrunning" : "notrunning";

[JsonIgnore]
public Boolean IsRunning { get; set; }

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 2020-05-27
    • 2020-12-02
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多