0

I want to create a Newtonsoft Json Enum converter, that in case I can't convert the string to an enum, I will log the original value and will assign the value Unknown.

This is my Enum:

public enum Size
{
    S,
    M,
    L,
    XL,
    UnknownSize
}

This is my converter:

public class SizesStringEnumConverter: StringEnumConverter
    {
        private readonly ILogger _logger;

        public SizesStringEnumConverter(ILogger logger)
        {
            _logger = logger;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                return base.ReadJson(reader, objectType, existingValue, serializer);
            }
            catch // e.g. in cases where Size is "XXXL"
            {
                _logger.Warning($"Couldn't convert value: {reader.Value} from JSON into a Size");
                return Size.UNKNOWN;
            }
        }
    }

Unfortunately, I can't use this JsonEnumConverter since it must have a parameterless constructor. When I try to add a parameterless constructor, the _logger instance is always null. Do you know how can I solve/fix it?

This is how I try to deserialize:

var logger = new LocalLogger();
var serializer = new SizesStringEnumConverter(logger);

string testJson = @" {
                ""Size"": ""XXXXXXL""
            }"
            ;

var shirt = JsonConvert.DeserializeObject<Shirt>(testJson, serializer)
Itay Barber
  • 63
  • 2
  • 9
  • This shouldn't be hard. But why are you still using newtonsoft? Not system.text.json? – JHBonarius Apr 16 '23 at 11:07
  • I would argue that this is an exception that should be handled in the method calling the `JsonConvert.Deserialize` method and not in the converter itself. – Zohar Peled Apr 16 '23 at 11:29
  • Assuming you are applying the converter via attributes, there are already a few questions on this topic, including [Adding parameter to Json converter during deserialization with converter defined for property](https://stackoverflow.com/q/75006063) and [How to inject dependency in Newtonsoft JsonConverter in .NET Core 3.1](https://stackoverflow.com/q/69520303). Do either of those answer your question also? – dbc Apr 16 '23 at 15:19
  • 1
    Can you please [edit] your question to share how you are applying `SizesStringEnumConverter`? Are you applying it via attributes on some property, or on the enum itself? ... – dbc Apr 16 '23 at 17:28
  • 1
    Because if you are only applying it by passing it into `JsonConvert.DeserializeObject()` directly then your code should work. But if you are passing it in directly and also applying it via attributes, and want the one passed in to supersede the one applied via attributes, then `OverridableJsonConverterDecorator` from [this answer](https://stackoverflow.com/a/41216067/3744182) to [Why Json.net does not use customized IsoDateTimeConverter?](https://stackoverflow.com/q/6384132/3744182) might work for you. – dbc Apr 16 '23 at 17:32

0 Answers0