0

In an endpoint Im developing I use the following command

var responseBodyDeserialized = await JsonSerializer.DeserializeAsync<TResponse>(response.Content.ReadAsStream());

The issue is that one of the fields its throwing an exception. Because the value can be for example:

  • 0 (number)
  • "10" (string)
  • "7+" (string)

the property of TResponse I already tried to give the type string and int and both are throwing exceptions.

    var jsonOptions = new JsonSerializerOptions()
    {
        NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals
    };

Using this JsonSerializerOptions and having the property with type int doesnt work because we can get a string like "7+".

Is there a string handler we can use?

The exception are like this:

{"The JSON value could not be converted to System.Int32. Path: $[111].xxxxxx | LineNumber: 0 | BytePositionInLine: 11569963."}

UPDATE:

One solution I found to solve this is to use the type object since the property can either be received from json as int or string types. And then since I want to convert it to another DTO I'm using AutoMapper library and user a map like the one above:

CreateMap<FeedElemDto, ResultDto>()
    .ForMember(dest => dest.xxxx, opt => opt.MapFrom(src => Convert.ToString(src.xxxx)));

Would like to know if this is an OK solution.

4
  • So what "7+" should result in? Commented Mar 20, 2023 at 17:48
  • Maybe use JsonValue or something like that? Commented Mar 20, 2023 at 18:39
  • @GuruStron the field is related with ages, I would say it means it's 7 or more, tbh I would just consider the field as a string I dont know how to deal with that with an int. Commented Mar 20, 2023 at 19:08
  • @Fildor ok, can you elaborate? thanks. Commented Mar 20, 2023 at 19:08

1 Answer 1

0

You can use the accepted answer to this similar question here.

They add a custom converter on the property you want using the JsonConverterAttribute (or you can add it to the list of converters) and inside the custom converter get the raw doc for this segment. To clarify, using string as your property type and add a custom converter as shown below and call DeserializeAsync as before.

await JsonSerializer.DeserializeAsync<MyType>(stream);

public sealed class FormatAsTextConverter : JsonConverter<string>
{
    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using (var jsonDoc = JsonDocument.ParseValue(ref reader))
        {
            return jsonDoc.RootElement.GetRawText();
        }
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}
public class MyType
{
    [JsonConverter(typeof(FormatAsTextConverter))]
    public string Prop { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.