❔ Using a Custom JSON Converter on NswagStudio's Generated C# Client

Does anyone know how I can make NswagStudio use a custom json converter that I made on the generated C# client?
public class CustomDateTimeOffsetConverter : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
DateTimeOffset? value = null;

if (string.IsNullOrEmpty(reader.Value?.ToString())
|| !DateTimeOffset.TryParse(reader.Value?.ToString(), out DateTimeOffset output))
{
return value;
}

if (output < DateTimeOffset.MaxValue)
{
value = output;
}

return value;
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (string.IsNullOrEmpty(value?.ToString())
|| !DateTimeOffset.TryParse(value.ToString(), out DateTimeOffset output)
|| (DateTimeOffset.TryParse(value.ToString(), out output) && output == DateTimeOffset.MaxValue))
{
writer.WriteNull();
}

writer.WriteValue(value);
}
}
public class CustomDateTimeOffsetConverter : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
DateTimeOffset? value = null;

if (string.IsNullOrEmpty(reader.Value?.ToString())
|| !DateTimeOffset.TryParse(reader.Value?.ToString(), out DateTimeOffset output))
{
return value;
}

if (output < DateTimeOffset.MaxValue)
{
value = output;
}

return value;
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (string.IsNullOrEmpty(value?.ToString())
|| !DateTimeOffset.TryParse(value.ToString(), out DateTimeOffset output)
|| (DateTimeOffset.TryParse(value.ToString(), out output) && output == DateTimeOffset.MaxValue))
{
writer.WriteNull();
}

writer.WriteValue(value);
}
}
2 Replies
absolution183
absolution183OP2y ago
Looks like I found the solution. I added CustomDateTimeOffsetConverter on the nswag config file.
"jsonConverters": [
"CustomDateTimeOffsetConverter"
]
"jsonConverters": [
"CustomDateTimeOffsetConverter"
]
And I regenerated the C# client.
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server