jsonasp.net-mvcpostasp.net-web-apihttp-post

Assign json or text value to model View


I have a model view class:

public class ClientModelView : BaseModelView
{
    public int ClientId { get; set; }
    public int? ClientTypeId { get; set; }
    public int? DisciplineId { get; set; }
    public string ClientName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }

    public AddressModelView Address { get; set; }
    public ClientTypeModelView ClientType { get; set; }
    public DisciplineModelView Discipline { get; set; }
    public bool EmailConfirmed { get; set; }
}

I am working on Stripe integration to send client info to my application through a webhook.

I am sending JSON data post request to my application endpoint. I am getting it in string format. I need to convert that JSON request to model view controller.

The JSON request looks like this:

{ 
    "ClientName":"ABC client",
    "firstName": "ABC",
    "lastName": "Client",
    "email": "abc@test.com",
    "Address":
        [
            { 
                "Type":"Client", 
                "DisplayAddress":"123 test Dr, test WA 6010",
                "Street1":"123 test Dr",
                "Suburb":"test",
                "Postcode":"6010",
            }
        ]
}

I have the following webhook code:

[HttpPost]
public async Task<IHttpActionResult> Index()
{
    string result = await Request.Content.ReadAsStringAsync();
    ClientModelView client = result; //failed to assign json request string to client model object
    return ok();
}

How to to assign JSON request string to client model object?


Solution

  • Why do you think that you can assign a string value to a ClientModelView object? That clearly doesn't type-check.

    You can try to parse the string as the object you desire. Using JsonSerializer.Deserialize something like this ought to work:

    [HttpPost]
    public async Task<IHttpActionResult> Index()
    {
        string result = await Request.Content.ReadAsStringAsync();
        var client = JsonSerializer.Deserialize<ClientModelView>(result);
        return ok();
    }