Skip to main content
 首页 » 编程设计

c#之使用属性和 ServiceStack.Text.JsonSerializer 的自定义序列化

2024年02月05日1598°冷暖

我们使用自定义属性来注释数据应该如何显示:

public class DcStatus 
{ 
    [Format("{0:0.0} V")]   public Double Voltage { get; set; } 
    [Format("{0:0.000} A")] public Double Current { get; set; } 
    [Format("{0:0} W")]     public Double Power => Voltage * Current; 
} 

使用属性提供的格式,使用 String.Format 处理属性。

我们需要如何配置 ServiceStack.Text.JsonSerializer 以使用该属性?

例子:

var test = new DcStatus {Voltage = 10, Current = 1.2}; 
var json = JsonSerializer.SerializeToString(test); 

应该产生

{ 
    "Voltage": "10.0 V", 
    "Current": "1.200 A", 
    "Power"  : "12 W", 
} 

请您参考如下方法:

没有可自定义的回调,可让您修改内置类型如何根据自定义属性属性进行序列化。

为此类型获得所需自定义序列化的一个选项是实现 ToJson() ServiceStack.Text 使用的方法,例如:

public class DcStatus 
{ 
    [Format("{0:0.0} V")] 
    public Double Voltage { get; set; } 
    [Format("{0:0.000} A")] 
    public Double Current { get; set; } 
    [Format("{0:0} W")] 
    public Double Power => Voltage * Current; 
 
    public string ToJson() 
    { 
        return new Dictionary<string,string> 
        { 
            { "Voltage", "{0:0.0} V".Fmt(Voltage) }, 
            { "Current", "{0:0.000} A".Fmt(Current) }, 
            { "Power", "{0:0} W".Fmt(Power) }, 
        }.ToJson(); 
    } 
} 

打印出想要的结果:

var test = new DcStatus { Voltage = 10, Current = 1.2 }; 
test.ToJson().Print(); //= {"Voltage":"10.0 V","Current":"1.200 A","Power":"12 W"} 

否则,如果您不想更改现有类型,您还可以通过注册 JsConfig<T>.RawSerializeFn 来自定义现有类型的序列化。 impl 并返回您想要使用的自定义 JSON,例如:

 JsConfig<DcStatus2>.RawSerializeFn = o => new Dictionary<string, string> { 
    { "Voltage", "{0:0.0} V".Fmt(o.Voltage) }, 
    { "Current", "{0:0.000} A".Fmt(o.Current) }, 
    { "Power", "{0:0} W".Fmt(o.Power) }, 
}.ToJson();