Service which I work with uses strange serialization. When array is empty it looks like this:
"SomeArr":[]
But when 'SomeArr' has items it looks like this:
"SomeArr":
{
"item1": { "prop1":"value1" },
"item2": { "prop1":"value1" }
...
}
So it's not even array now but JObject with properties instead of array enumerators
I have this converter that must be applied to all properties with List type
public class ArrayObjectConverter<T> : JsonConverter<List<T>>
{
public override void WriteJson(JsonWriter writer, List<T>? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override List<T>? ReadJson(JsonReader reader, Type objectType, List<T>? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
List<T> result = new();
if (reader.TokenType == JsonToken.StartArray)
{
var jArray = JArray.Load(reader);
//'LINQ Select' because sometimes arrays are normal
//So if I set this converter as default we select objects from this array
return jArray.Select(jt => jt.ToObject<T>()!).ToList();
}
else
{
var jObject = JObject.Load(reader);
foreach (var kvp in jObject)
{
var obj = kvp.Value!.ToObject<T>()!;
result.Add(obj);
}
return result;
}
}
}
So how I can set this converter as default (e.g. in serializer.settings). The problem is this converter is generic type and I can't set in settings without generic argument.
Of course I can put [JsonConverter(typeof(ArrayObjectConverter<T>))] attribute for every collection. But my json classes already have a lot of boilerplate. Any suggestions?
P.S. The solution should be as optimized as possible because the speed of deserialization is very important.