Home > Enterprise >  Converting Json Element to Array
Converting Json Element to Array

Time:04-09

I have the following JSON being sent from Postman to my Web API.

[
    {
        "salesId": "SO002494"
    },
    {
        "salesId": "SO002496"
    } 
]

Sales Model

public class Sales
        {
            public string[] salesId { get; set; }
        }
[HttpGet("postRouteOrder")]
        public async Task<ActionResult<string>>PostRouteOrder([FromBody] Object json)
        {
            Sales sales = new Sales();

            sales.salesId = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json.ToString());
           
            //string[] data = { "SO002604", "SO002606" };               
        }

I want sales.salesId to be like data.

CodePudding user response:

Would suggest changing the request body parameter type to List<SaleInput>.

using System.Linq;

[HttpPost]
public async Task<ActionResult<string>> PostRouteOrder ([FromBody] List<SaleInput> saleInputs)
{
    Sales sales = new Sales();

    sales.salesId = saleInputs.Select(x => x.SalesId)
        .ToArray();
}
public class SaleInput
{
    public string SalesId { get; set; }
}

Apart from that, instead of deserializing as dynamic, you should deserialize as List of objects and take the SalesId as an array.

List<SaleInput> saleInput = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SaleInput>>(/* JSON */);

sales.salesId = saleInputs.Select(x => x.SalesId)
        .ToArray();
  • Related