Mike Witt Mike Witt - 3 years ago 151
JSON Question

JSON deserialization error in WebApi with array

I'm posting the following JSON payload from a JavaScript Angular app to a webapi service:

{Notes: "test", Ids: [606, 603]}

this.http.post(url, {"Notes": "test", "Ids": [606,603]}, options)

I'm attempting to deserialize this into a .net Dictionary like:

public IHttpActionResult Test(Dictionary<string,string> formData)

(I've tried to add the [FromBody] decorator too).

If I don't include the array, this works fine. But with the array, I get a couple of parse error:

Unexpected character encountered while parsing value: [. Path 'Ids', line 1, position 23.
Invalid JavaScript property identifier character: ]. Path 'Ids', line 1, position 30.

Answer Source

The "JSON" you're posting is not valid JSON - you can use a tool like JSONLint to validate your JSON.

The correct JSON syntax for your data is:

    "Notes": "test",
    "Ids": [606, 603]

Also - the method takes a Dictionary<string,string> object. Your array is not a string, and the controller will therefore fail while trying to deserialize the array into a string.

My suggestion is to create a model, which the controller method should receive. Like this:

public IHttpActionResult Test(YourModel data)

class YourModel 
    public string Notes {get;set;}
    public int[] Ids {get;set;}

Using this code, the controller will deserialize your JSON (when you have corrected the JSON syntax problems) into an instance of YourModel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download