0

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:

[HttpPost]
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.

1
  • Not all values in the payload are string. use Dictionary<string,object> Commented Jul 26, 2017 at 15:19

1 Answer 1

1

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:

[HttpPost]
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.

Sign up to request clarification or add additional context in comments.

5 Comments

Since my javascript looks like: this.http.post(url, {"Notes": notes, "Ids": idList}, options) - Any idea how to get it to format correctly? Also, the parse error notes that it found an error parsing "[". I'm going to add the javascript to the OP.
One other thought, if I send just: {Notes: "test"} in the payload (javascript being {"Notes": "test"}), it is accepted. So I think it is a problem with the array.
@MikeWitt - You're correct, the array is also a problem. I've updated my answer.
@.J.N. - Thanks, couldn't see the forest for the trees I guess :). Using Dictionary<string,object> worked.
@MikeWitt. You're welcome - using a dedicated model which the controller can be used to deserialize to will, in the long run, make it much easier for you to work with the data IMO. But great that you got it working!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.