0

Map JSON object to class c# property Use case : I am creating API in Azure Function and passing parameter-ReservationDraftRequestDto class like below code

[FunctionName("Function1")] public static async Task Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] ReservationDraftRequestDto reservationDraftRequestDto, ILogger log) { }

DTO class:

API URI: http://localhost:7071/api/Function1 JSON-for calling API is: { "SoftHoldIDs": 444, "AppliedUsages": [ { "SoftHoldID": 444, "UsageYearID": 4343, "DaysApplied": 0, "PointsApplied": 1 } ], "Guests": [ 1, 2 ] }

public class ReservationDraftRequestDto
{

    public int SoftHoldIDs { get; set; }
    public int[] Guests { get; set; }
    public AppliedUsage[] AppliedUsages { get; set; }

}


public class AppliedUsage
{
    public int SoftHoldID { get; set; }
    public int UsageYearID { get; set; }
    public int DaysApplied { get; set; }
    public int PointsApplied { get; set; }
}

Issue is: When i called API with above payload then API class parameter-ReservationDraftRequestDto not mapped AppliedUsages array values.

Please let me know what i need to do map API JSON payload to ReservationDraftRequestDto

Send Request-enter image description here

Code: enter image description here

1 Answer 1

2

It is by design.The binding logic is explicitly excluding arrays while deserializing the json body contents.You could refer to here.

If you want to get the object,here is a simple workaround:

[FunctionName("Function1")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req,
    ILogger log)
{
    var reservationDraftRequestDto = req.DeserializeModel<ReservationDraftRequestDto>();

    var data = JsonConvert.SerializeObject(reservationDraftRequestDto);
    //more logic...
    return new OkResult();
}
public static T DeserializeModel<T>(this HttpRequest request)
{
    using (var reader = new StreamReader(request.Body))
    using (var textReader = new JsonTextReader(reader))
    {
        request.Body.Seek(0, SeekOrigin.Begin);
        var serializer = JsonSerializer.Create(new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
        return serializer.Deserialize<T>(textReader);
    }
}

Result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.