Liam G
Liam G

Reputation: 791

Receive JSON from body and iterate over it

I am trying to create a PUT method (or POST, whichever works) which takes in JSON (content-type:application/json) as the body and then iterates over it, writing the (key, value) contents to the console. I am unsure how to take the JSON as an input, as using [FromBody] string data returns the following error: "The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1.".

So to fix this I am using the dynamic type. However, I am then unable to iterate over the key-value pairs of this datatype. The input JSON will be random every time so I can't create a class for it.

PUT method:

[HttpPut("{something}")]
public ActionResult update(string something, [FromBody] dynamic data)
{

}

Sample JSON:

{"id":"123","name":"sample name"}

What I've tried:

The following line: var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);

outputs an error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string,string>>(string)' has some invalid arguments

Expected output to the console after successful iteration over the JSON data:

id: 123
name: some name

Upvotes: 0

Views: 261

Answers (1)

Liam G
Liam G

Reputation: 791

Just as soon as I post the question - I find the answer

[HttpPut("{something}")]
public ActionResult update(string something, [FromBody] Dictionary<string, string> data)
{
    foreach (KeyValuePair<string, string> value in data)
    {
        Console.WriteLine(value);

    }
}

I can take a dictionary as an input - which presumably allows C# to deserialize the JSON for me.

Upvotes: 1

Related Questions