11using System ;
22using Bogus ;
3+ using Nest ;
4+ using Newtonsoft . Json ;
5+ using Newtonsoft . Json . Serialization ;
36
47namespace Tests . Framework . MockData
58{
@@ -13,6 +16,14 @@ public class CommitActivity
1316 public Developer Committer { get ; set ; }
1417 public TimeSpan ? Duration { get ; set ; }
1518
19+ [ String ]
20+ [ JsonConverter ( typeof ( StringTimeSpanConverter ) ) ]
21+ public TimeSpan ? StringDuration
22+ {
23+ get { return Duration ; }
24+ set { Duration = value ; }
25+ }
26+
1627 public static Faker < CommitActivity > Generator { get ; } =
1728 new Faker < CommitActivity > ( )
1829 . RuleFor ( p => p . Id , p => Guid . NewGuid ( ) . ToString ( "N" ) . Substring ( 0 , 8 ) )
@@ -25,12 +36,45 @@ public class CommitActivity
2536 {
2637 TimeSpan . MinValue ,
2738 TimeSpan . MaxValue ,
28- null ,
29- TimeSpan . Zero ,
3039 TimeSpan . FromMinutes ( 7.5 ) ,
40+ TimeSpan . Zero ,
41+ null ,
3142 TimeSpan . FromHours ( 4.23 ) ,
3243 TimeSpan . FromDays ( 5 ) ,
3344 } ) )
3445 ;
3546 }
47+
48+ internal class StringTimeSpanConverter : JsonConverter
49+ {
50+ public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer )
51+ {
52+ if ( value == null )
53+ writer . WriteNull ( ) ;
54+ else
55+ {
56+ var timeSpan = ( TimeSpan ) value ;
57+ writer . WriteValue ( timeSpan . ToString ( ) ) ;
58+ }
59+ }
60+
61+ public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer )
62+ {
63+ if ( reader . TokenType == JsonToken . Null )
64+ {
65+ if ( ! objectType . IsGeneric ( ) || objectType . GetGenericTypeDefinition ( ) != typeof ( Nullable < > ) )
66+ throw new JsonSerializationException ( $ "Cannot convert null value to { objectType } .") ;
67+
68+ return null ;
69+ }
70+ if ( reader . TokenType == JsonToken . String )
71+ {
72+ return TimeSpan . Parse ( ( string ) reader . Value ) ;
73+ }
74+
75+ throw new JsonSerializationException ( $ "Cannot convert token of type { reader . TokenType } to { objectType } .") ;
76+ }
77+
78+ public override bool CanConvert ( Type objectType ) => objectType == typeof ( TimeSpan ) || objectType == typeof ( TimeSpan ? ) ;
79+ }
3680}
0 commit comments