skip to Main Content

I have a requirement in which I must have property that can bind it’s value by "debtAmount" or "Amount"

class

I did try to have annotation from above, and it works for debtAmount but value won’t bind using "amount"

Binds on debtAMount

I want to achieve one an optional binding for one property (either by amount or debtAmount)

2

Answers


  1. if you want multiple JSON properties during deserialization, you can use JsonConverter

    public class NewAccountRequestJsonConverter : JsonConverter<NewAccountRequest>
    {
        public override NewAccountRequest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var newAccountRequest = new NewAccountRequest();
    
            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                    return newAccountRequest;
    
                if (reader.TokenType == JsonTokenType.PropertyName)
                {
                    string propertyName = reader.GetString();
    
                    if (propertyName == "amount" || propertyName == "debtAmount")
                    {
                        reader.Read();
                        newAccountRequest.Amount = reader.GetDecimal();
                    }
                    else
                    {
                        reader.Skip();
                    }
                }
            }
    
            throw new JsonException();
        }
    
        public override void Write(Utf8JsonWriter writer, NewAccountRequest value, JsonSerializerOptions options)
        {
            writer.WriteStartObject();
            writer.WriteNumber("amount", value.Amount);
            writer.WriteEndObject();
        }
    }
    

    During Deserialize use this NewAccountRequestJsonConverter as options

     var options = new JsonSerializerOptions();
     options.Converters.Add(new NewAccountRequestJsonConverter());
    
     var result = JsonSerializer.Deserialize<NewAccountRequest>(jsonString, options);
    
    Login or Signup to reply.
  2. One approach, already presented is to put some mapping logic inside JsonConverter (inherit from it and override some logic).

    Second approach, as I see, could be mapping both fields to their respective fields Amount and debtAmount and have some method to fetch that info based on both properties, something along those lines:

    public static class Extensions
    {
        public static decimal? GetAmount(this NewAccountRequest request) =>
            request.Ammount ?? request.DebtAmount;
    }
    

    You would need to make amount fields nullable, to detect when they’re not provided at all. Or you can treat default value of 0 as "empty value", if 0 won’t be valid number.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search