0

From the client, I would like to pass a collection of json nodes: [{key, value},{key, value}] to a WebAPI endpoint. what should my api endpoint param type be? a List<>() or something else?

This would be using C#.

I need to iterate over each endpoint that is passed in the collection.

4
  • If it's a key value, would you not just use a dictionary? Commented May 12, 2017 at 15:22
  • perhaps. Would that be the proper way or just a different way? Commented May 12, 2017 at 15:29
  • so List<Dictionary<string, string>>()?? could be proper? Commented May 12, 2017 at 15:37
  • List<Dictionary<string, string>>() is redundunent. Just a dictionary<string,string> Commented May 12, 2017 at 18:33

1 Answer 1

1

In general, it is good practice to create a model that your JSON will be deserialized into. To answer your question though if your JSON was in the format

[{key1: value1},{key2: value2}] 

you would be able to use a

List<Dictionary<string,object>>()

If you were sure that your values were always string values you could do

List<Dictionary<string,string>>()

As JSON values can be strings (wrapped in quotes), integers (no quotes) or null.

So your Web API controller could be something like this:

[HttpPost]
public IHttpActionResult ReceiveJSON([FromBody]List<Dictionary<string,string>> in_json)
    {
        // And then one way to iterate over each 'json node' passed
        foreach(var dict in in_json)
        {
         // Do something with dictionary object
        }
        return Ok(in_sjon);
    }

What version of ASP.Net Web API will you be using?

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

4 Comments

It's actually going to be AspNetCore.Mvc 1.1.2
could I just use Dictionary<string, string>() as the param type and then just iterate over the dictionary?
Assuming your Json reflects the string you posted: no, you can't. That json is an array of objects, dictionaries can be mapped to objects, not arrays.
@GregBrethen Very good. I ran my example in ASP.Net Core so this should work for you.

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.