@@ -301,6 +301,64 @@ public void Can_customize_JSON_decimal()
301301 Assert . That ( dto . ToJsv ( ) , Is . EqualTo ( "{Decimal:1,33}" ) ) ;
302302 Assert . That ( dto . ToJson ( ) , Is . EqualTo ( "{\" Decimal\" :1,33}" ) ) ;
303303 }
304+
305+ public class FormatAttribute : Attribute
306+ {
307+ string Format ;
308+
309+ public FormatAttribute ( string format )
310+ {
311+ Format = format ;
312+ }
313+ }
314+
315+ public class DcStatus
316+ {
317+ [ Format ( "{0:0.0} V" ) ]
318+ public Double Voltage { get ; set ; }
319+ [ Format ( "{0:0.000} A" ) ]
320+ public Double Current { get ; set ; }
321+ [ Format ( "{0:0} W" ) ]
322+ public Double Power => Voltage * Current ;
323+
324+ public string ToJson ( )
325+ {
326+ return new Dictionary < string , string >
327+ {
328+ { "Voltage" , "{0:0.0} V" . Fmt ( Voltage ) } ,
329+ { "Current" , "{0:0.000} A" . Fmt ( Current ) } ,
330+ { "Power" , "{0:0} W" . Fmt ( Power ) } ,
331+ } . ToJson ( ) ;
332+ }
333+ }
334+
335+ public class DcStatus2
336+ {
337+ [ Format ( "{0:0.0} V" ) ]
338+ public Double Voltage { get ; set ; }
339+ [ Format ( "{0:0.000} A" ) ]
340+ public Double Current { get ; set ; }
341+ [ Format ( "{0:0} W" ) ]
342+ public Double Power => Voltage * Current ;
343+ }
344+
345+ [ Test ]
346+ public void Can_deserialize_using_CustomFormat ( )
347+ {
348+ var test = new DcStatus { Voltage = 10 , Current = 1.2 } ;
349+ Assert . That ( test . ToJson ( ) , Is . EqualTo ( "{\" Voltage\" :\" 10.0 V\" ,\" Current\" :\" 1.200 A\" ,\" Power\" :\" 12 W\" }" ) ) ;
350+
351+ JsConfig < DcStatus2 > . RawSerializeFn = o => new Dictionary < string , string > {
352+ { "Voltage" , "{0:0.0} V" . Fmt ( o . Voltage ) } ,
353+ { "Current" , "{0:0.000} A" . Fmt ( o . Current ) } ,
354+ { "Power" , "{0:0} W" . Fmt ( o . Power ) } ,
355+ } . ToJson ( ) ;
356+
357+ var test2 = new DcStatus2 { Voltage = 10 , Current = 1.2 } ;
358+ Assert . That ( test2 . ToJson ( ) , Is . EqualTo ( "{\" Voltage\" :\" 10.0 V\" ,\" Current\" :\" 1.200 A\" ,\" Power\" :\" 12 W\" }" ) ) ;
359+
360+ JsConfig . Reset ( ) ;
361+ }
304362 }
305363
306364}
0 commit comments