1

So i am in a situation where my NewtonJson custom converters do not work with from body api calls. ( its using System.Text.Json by default to convert).

so currently i had a temporary solution to write some wrappers which will ultimately call Newtonjson until the text.json converters are written and tested.

what i want to do is to read the entire object as a string and pass it along to newtons converter

my StartUp.cs

 services.AddControllers(options =>
        options.Filters.Add<ApiExceptionFilterAttribute>())
            .AddFluentValidation(x => x.AutomaticValidationEnabled = false)//ValidationBehaviour handle fluent validations.
            .AddJsonOptions(x =>
            {
                x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                x.JsonSerializerOptions.Converters.Add(new SystemModelConverter());
                x.JsonSerializerOptions.IgnoreNullValues = true;
            });

my converter class

 public class SystemModelConverter : JsonConverter<ISystemModel>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return (typeToConvert.GetInterface(typeof(ISystemModel).Name) != null);
    }

    public override ISystemModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var value = new StringBuilder();
        while(reader.Read())
        {
            var str = reader.GetString();
            value.Append(str);
        }
        //passing the string along
        return Newtonsoft.Json.JsonConvert.DeserializeObject(value.ToString(), CoreExtensions.GetJsonSerializerSettings()) as ISystemModel;
    }

    public override void Write(Utf8JsonWriter writer, ISystemModel value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
dbc
  • 104,963
  • 20
  • 228
  • 340
UndeadEmo
  • 433
  • 1
  • 6
  • 15
  • What does *body api calls* mean? Depending on what technology your using you can likely swap out the serialiser? – Liam Jan 13 '22 at 12:18
  • I suspect you'd spend more time trying to extract a raw JSON string from the `Utf8JsonReader` to pass to your Newtonsoft converter than it would take to rewrite your Newtonsoft converter. – Richard Deeming Jan 13 '22 at 14:11

1 Answers1

4

looks this this worked

 using (var jsonDocument = JsonDocument.ParseValue(ref reader))
        {
            var jsonText = jsonDocument.RootElement.GetRawText();
        }

Source

UndeadEmo
  • 433
  • 1
  • 6
  • 15