@@ -16,7 +16,7 @@ public class DataObjectSerializer : SerializerBase<object>
16
16
{
17
17
private static JsonSerializerSettings SerializerSettings = new JsonSerializerSettings ( )
18
18
{
19
- TypeNameHandling = TypeNameHandling . All
19
+ TypeNameHandling = TypeNameHandling . Objects ,
20
20
} ;
21
21
22
22
public override object Deserialize ( BsonDeserializationContext context , BsonDeserializationArgs args )
@@ -32,15 +32,45 @@ public override object Deserialize(BsonDeserializationContext context, BsonDeser
32
32
33
33
public override void Serialize ( BsonSerializationContext context , BsonSerializationArgs args , object value )
34
34
{
35
- string str = JsonConvert . SerializeObject ( value , SerializerSettings ) ;
35
+ var str = JsonConvert . SerializeObject ( value , SerializerSettings ) ;
36
36
var doc = BsonDocument . Parse ( str ) ;
37
- var typeElem = doc . GetElement ( "$type" ) ;
38
- doc . RemoveElement ( typeElem ) ;
39
-
40
- if ( doc . Elements . All ( x => x . Name != "_t" ) )
41
- doc . InsertAt ( 0 , new BsonElement ( "_t" , typeElem . Value ) ) ;
37
+ ConvertMetaFormat ( doc ) ;
42
38
43
39
BsonSerializer . Serialize ( context . Writer , doc ) ;
44
40
}
41
+
42
+ private static void ConvertMetaFormat ( BsonDocument root )
43
+ {
44
+ var stack = new Stack < BsonDocument > ( ) ;
45
+ stack . Push ( root ) ;
46
+
47
+ while ( stack . Count > 0 )
48
+ {
49
+ var doc = stack . Pop ( ) ;
50
+
51
+ if ( doc . TryGetElement ( "$type" , out var typeElem ) )
52
+ {
53
+ doc . RemoveElement ( typeElem ) ;
54
+
55
+ if ( doc . Elements . All ( x => x . Name != "_t" ) )
56
+ doc . InsertAt ( 0 , new BsonElement ( "_t" , typeElem . Value ) ) ;
57
+ }
58
+
59
+ foreach ( var subDoc in doc . Elements )
60
+ {
61
+ if ( subDoc . Value . IsBsonDocument )
62
+ stack . Push ( subDoc . Value . ToBsonDocument ( ) ) ;
63
+
64
+ if ( subDoc . Value . IsBsonArray )
65
+ {
66
+ foreach ( var element in subDoc . Value . AsBsonArray )
67
+ {
68
+ if ( element . IsBsonDocument )
69
+ stack . Push ( element . ToBsonDocument ( ) ) ;
70
+ }
71
+ }
72
+ }
73
+ }
74
+ }
45
75
}
46
76
}
0 commit comments