JBA
JBA

Reputation: 220

Converting JSON post data into array of objects

Server side : ASP.NET WEB-API 2.0

I am posting a bunch of name value pairs from client side to server side as JSON. On the server side (WEB API controller), I would like to convert them into array/list of object containing the name and value.

JSON post data :

[{"name":"sEcho","value":9},
{"name":"iColumns","value":6},
{"name":"sColumns","value":"Name1,Name2,Name3,Name4,Name5,Name6"},     
{"name":"iDisplayStart","value":0},
{"name":"iDisplayLength","value":10},
{"name":"mDataProp_0","value":0},
{"name":"mDataProp_1","value":1},
{"name":"mDataProp_2","value":2},
{"name":"mDataProp_3","value":3}]

I tried to map it in server side using the following mode but it did not work

public IHttpActionResult Post([FromBody]GridDataModel gridData)

Models

public class GridDataModel
{
    public GridData[] GridData { get; set; }
}

public class GridData
{
    public string Name { get; set; }
    public string Value { get; set; }
}

I am used to mapping a JSOn strcuture like this a single object with each name value mapping to an object attribute. Not sure how I can convert it into an array of objects. I need it to be an array because the number of name value pairs will be dynamic.

Any help will be appreciated!

Thanks in advance..

Upvotes: 3

Views: 1175

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68440

The method is expecting a single instance and not an array. I believe you could do 2 things

1) Change the method signature

public IHttpActionResult Post([FromBody]IEnumerable<GridData> gridData)

2) Change the json object

{"gridData": [{"name":"sEcho","value":9},
{"name":"iColumns","value":6},
{"name":"sColumns","value":"Name1,Name2,Name3,Name4,Name5,Name6"},     
{"name":"iDisplayStart","value":0},
{"name":"iDisplayLength","value":10},
{"name":"mDataProp_0","value":0},
{"name":"mDataProp_1","value":1},
{"name":"mDataProp_2","value":2},
{"name":"mDataProp_3","value":3}]}

Upvotes: 4

Related Questions