jjaskulowski
jjaskulowski

Reputation: 2564

Deserialize JSON array with skipped elements

I'm sending that kind of json to asp.net web api action.

{
  "keys": {
     "2a":["C",,,,,"0",,"0"]
  }
} 

This json is POST-ed exactly as it is in request body to my asp.net 4.5 web api 2 action.

[RoutePrefix("api/TImport")]
[Authorize]
public class TImportController : ApiController
{

    [Route("")]
    [HttpPost]
    public async Task<TImportResult> Post(TImportParameters parameters)
    {
        // parameters.Keys["2a"] got deserialized as array[3] {"C","0","0" }   :(( 
        return await new TImport().RunAsync(parameters);
    }

What happens is that the 2a is deserialized into array of 3 elements instead of 8 elements with null or empty elements 2 to 6 and 7.

What can I do to to desserialize skipped array elements as defaults (nulls or empty strings)?

Upvotes: 1

Views: 71

Answers (1)

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

that is an invalid json string. Though some json parsers ignore the bad syntax. And C#/javascript doesn't allow you to create properties that starts with numbers(2a in this case)[JSON.Net doesn't complain though]. A json string should contain key/values separated by comma(,).

Upvotes: 1

Related Questions