Search code examples
asp.netjsonapijsonconverter

JsonConvert.DeserializeObject<> is returning null last childtoken of the two childrentokens


I am sending a JObject from the frontend to my API, which is divided into First and Last childtokens, as seen in the picture below:

The sample JObject request

However, when I am trying to use the following code, the last part of childrendtoken is becoming null

var RVoucher = JsonConvert.DeserializeObject<VMReceive>(request.ToString());

This is what I am having in the debugging mode:

The last child is null

Here, the VMReceive is a viewModel that consists of another viewmodel "VMMonth"and an ado.net generated model class "ReceiveVoucher". Code of the models are given below:

public class VMReceive
{
    public List<VMMonth> Month { get; set; }
    public ReceiveVoucher receiveVoucher { get; set; }
}

public class VMMonth
{
    public int item_id { get; set; }
    public string item_text { get; set; }
}

public partial class ReceiveVoucher
{
    public int ReceiveVoucherId { get; set; }
    public Nullable<int> MonthId { get; set; }
    public string ReceivedBy { get; set; }
    public string Remarks { get; set; }
    public Nullable<int> ReceivedAmount { get; set; }
}

I have also tried putting [JsonProperty("")] over each property of my "ReceiveVoucher" model class, but got the same 'null' issue.

I am not sure about what I am doing wrong here, your suggestion regarding this will be very helpful.


Solution

  • Your JSON property name doesn't match. Your class uses receiveVoucher whereas the JSON is ReceiveAmount. Also, why are you using JObject in the first place, this should work by just using the class name as the action parameter:

    public HttpResponse PostReceive([FromBody] VMReceive RVoucher, int userId)
    {
        ...
    }