I have a requirement in which I must have property that can bind it's value by "debtAmount" or "Amount"
I did try to have annotation from above, and it works for debtAmount but value won't bind using "amount"
I want to achieve one an optional binding for one property (either by amount or debtAmount)
The top answer for on this thread doesn't fit the maintainability requirement because eventually it will have additional properties that will require multiple name binding. So I don't want much additional private property for each public property.
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);