Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Http Post receive json from body

Tags:

json

c#

http-post

I have this HttpPost method:

[HttpPost]    
public string Test([FromBody]List<Account> accounts)
{
   var json = JsonConvert.SerializeObject(accounts);
   Console.Write("success");
   return json;
}

and this is my Account class:

public class Account
{
    public int accountId;
    public string accountName;
    public string createdOn;
    public string registrationNumber;
}

This is my json file which i send with postman:

{
    "Account": [
    {
        "accountId": "1",
        "accountName": "A purple door",
        "createdOn": "25-07-2017",
        "registrationNumber": "purple"
    },
    {
        "accountId": "2",
        "accountName": "A red door",
        "createdOn": "26-07-2017",
        "registrationNumber": "red"
    },
    {
        "accountId": "3",
        "accountName": "A green door",
        "createdOn": "27-07-2017",
        "registrationNumber": "green"
    },
    {
        "accountId": "4",
        "accountName": "A yellow door",
        "createdOn": "25-07-2017",
        "registrationNumber": "yellow"
    }
    ]
}

If i send this json my method doesn't work and it returns a null object. The only way to make it work is by sending the object only without the "Account" like this:

[
    {
      "accountId": "1",
      "accountName": "A purple door",
      "createdOn": "25-07-2017",
      "registrationNumber": "purple"
    },
    {
      "accountId": "2",
      "accountName": "A red door",
      "createdOn": "26-07-2017",
      "registrationNumber": "red"
    },
    {
      "accountId": "3",
      "accountName": "A green door",
      "createdOn": "27-07-2017",
      "registrationNumber": "green"
    },
    {
      "accountId": "4",
      "accountName": "A yellow door",
      "createdOn": "25-07-2017",
      "registrationNumber": "yellow"
    }
]

But i want the previous file format. How could my method receive the previous JSON ?

like image 305
kostasandre Avatar asked Oct 15 '25 22:10

kostasandre


1 Answers

Try to use this contract to achieve your requirement.

public class Rootobject
{
    public Account[] Account { get; set; }
}

public class Account
{
    public string accountId { get; set; }
    public string accountName { get; set; }
    public string createdOn { get; set; }
    public string registrationNumber { get; set; }
}

Method should be like this.

[HttpPost]    
public string Test([FromBody]Rootobject accounts)
{
   var json = JsonConvert.SerializeObject(accounts);
   Console.Write("success");
   return json;
}
like image 147
Power Star Avatar answered Oct 18 '25 10:10

Power Star



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!