1

I am using ASP.NET Core 2.1 with Web API and posting works fine when I send one object. How can I send this type here.

Until now I have tried this approach, https://ibb.co/dKztDGv, but without success. I don't get an error but I get the values from the last object only. Please help me get all the values in the array.

//I post this type of objects in array 
[
 {something...},
 {something...}
]

//what I've tried
public IActionResult PostNewLanguages([FromBody] JObject newLanguages, string id)
{
    var oneUser = GetSpecificUser(id);
    JObject class1DataJson = newLanguages;
    return Ok();
}

DerStarkeBaer
  • 669
  • 8
  • 28
Code
  • 313
  • 1
  • 2
  • 11

2 Answers2

0

When I run this and send an array of objects I get this error

InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.

So I suggest trying to send something like this instead

{ "myData": [
    {something...},
    {something...}
]}

And then to access the data you will need to do

var myValues = newLanguages["myData"];

foreach(var value in myValues)
{
}

'myData' being whatever key you use for your array. Looks like 'request' in your case going by your comments.

Dave Barnett
  • 2,045
  • 2
  • 16
  • 32
0

If you post an array of object, you need to receive it as a List like

public IActionResult PostNewLanguages([FromBody] List<JObject> newLanguages, string id)
{
    foreach(var obj in newLanguages)
    {

    }

    return Ok();
}
Ryan
  • 19,118
  • 10
  • 37
  • 53