Below class is the recursive dictionary (tree-like structure). The EntityID
is just the alias of string
which must be accessed via HierarchicalRelationshipsMap.EntityID
.
public class HierarchicalRelationshipsMap: Dictionary<HierarchicalRelationshipsMap.EntityID, HierarchicalRelationshipsMap>
{
public class EntityID
{
public static implicit operator EntityID(string value) => new EntityID();
public static implicit operator string(EntityID entityID) => string.Empty;
}
}
Instance example:
HierarchicalRelationshipsMap hierarchicalRelationshipsMap = new()
{
{
Guid.NewGuid().ToString(),
new HierarchicalRelationshipsMap
{
{Guid.NewGuid().ToString(), new HierarchicalRelationshipsMap() },
{Guid.NewGuid().ToString(), new HierarchicalRelationshipsMap() }
}
}
};
If to serialize it using
Newtonsoft.Json.JsonConvert.SerializeObject(hierarchicalRelationshipsMap, Newtonsoft.Json.Formatting.Indented));
it will produce this result:
{
"MockDataSource.HierarchicalRelationshipsMap+EntityID": {
"MockDataSource.HierarchicalRelationshipsMap+EntityID": {},
"MockDataSource.HierarchicalRelationshipsMap+EntityID": {}
}
}
while something like this would be expected:
{
"2ca15c6b-e706-4f1c-b287-1629ed0bac0a": {
"21333569-4248-49ac-ba0c-d1612a2c42a8": {}
"fc7ad745-8890-4a68-9431-c8de4801470b": {}
}
}
How to fix this?
2
Answers
The issue stems from the way
JsonConvert
interpretsEntityID
. Since it is a class, Json.NET doesn’t apply the implicit operator and instead serializes the actual type name. To address that just add implementation ofToString()
inEntityID
and make it return a GUID. You can also implement custom converter for that class and use it instead.Well, your implicit operators are just creating empty object/string, whatever data is generated (GUIDs) you discard it with the operators.
To fix that you need to define:
Then you would need to define custom
JsonConverter
, as by default it seesEntityID
as object and serializes it as such. We need to "instruct it" to do serialization differently:Then following code snippet:
Produces expected output: