C#C
C#3y ago
Noriega

✅ Newtonsoft serializing returns nothing with custom converter

So I have a custom JsonConverter from newtonsoft that is supposed to replace object properties that are a specific type. For context, I'm looking for a type called IOptional that has properties HasValue and Value only if HasValue is true. If HasValue is true, the converter is supposed to replace the json property with Value. Otherwise, it replaces to null.

I have this
file class EvalResultConverter : JsonConverter
{
    public override bool CanRead => false;
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType) => true;

    public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        => throw new NotImplementedException();

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        var token = JToken.FromObject(value!);
        
        if (token.Type is JTokenType.Object)
        {
            var tokenObject = (JObject)token;
            foreach (var property in tokenObject.Properties())
            {
                if (property.Value.Type is JTokenType.Object && typeof(IOptional).IsAssignableFrom(value!.GetType().GetProperty(property.Name)!.PropertyType))
                {
                    var propertyObject = (JObject)property.Value;
                    tokenObject[property.Name] = propertyObject["HasValue"]!.Value<bool>() ? propertyObject["Value"] : null;
                }
            }
                
            tokenObject.WriteTo(writer);
        }
        else token.WriteTo(writer);
    }
}

So just to be clear, any other token types works fine along with any objects that don't have IOptional properties. But when I try this with types that do, serialization returns nothing. Not sure if im incorrectly writing to the jsonwriter, but its been annoying for a few days
Was this page helpful?