I’m making a POST call containing multiple object arrays that have been serialized using JSON.stringify(). When I intercept the payload in my API call, I’m unsure of how exactly you’re supposed to deserialize the data to pull out the arrays. Here is some simplified code to illustrate my problem:
PersonData model and POST call
export class PersonData {
name: string;
age: number;
}
sendPersonData() {
const url = "http://localhost:5001/check-person-data";
let pd1 = new PersonData();
pd1.name = "Person1";
pd1.age = 1;
let pd2 = new PersonData();
pd2.name = "Person2";
pd2.age = 2;
let pd3 = new PersonData();
pd3.name = "Person3";
pd3.age = 3;
let pd4 = new PersonData();
pd4.name = "Person4";
pd4.age = 4;
var array1: PersonData[] = [pd1, pd2];
var array2: PersonData[] = [pd3, pd4];
let dictionary = {};
dictionary["Array1"] = array1;
dictionary["Array2"] = array2;
return this._http.post(url, JSON.stringify(dictionary), this.opts);
}
PersonData class and API endpoint:
public class PersonData
{
string name;
int age;
}
[HttpPost("/check-person-data")]
public IActionResult CheckPersonData([FromBody] dynamic data)
{
// Need to take payload and pull out each array.
// THESE BOTH THROW ERRORS
var person1 = (PersonData[])data.Array1;
var person2 = data.Array2 as PersonData[];
return null;
}
What’s the proper way to get each array out of the dynamic json string object? I’m not sure if my method of putting both arrays into the ‘let dictionary = {}’ and stringifying it is good practice – it’s just what works easily for me when sending primitives like strings and numbers. If this isn’t good practice, what should I be doing instead?
EDIT:
These are the errors I get for both lines:
'System.Text.Json.JsonElement' does not contain a definition for 'Array1'
'System.Text.Json.JsonElement' does not contain a definition for 'Array2'
Also, the payload comes in as:
"{"Array1":[{"name":"Person1","age":1},{"name":"Person2","age":2}],
"Array2":[{"name":"Person3","age":3},{"name":"Person4","age":4}]}"
3
Answers
Could you provide the thrown error? I would suggest using
var person1 = JsonSerializer.Deserialize<PersonData[]>(data.Array1);
in your backend or perhapsvar dict = JsonSerializer.Deserialize<Dictionary<string, PersonData[]>>(data); var person1 = dict["Array1"];
You could use
Dictionary<string, PersonData[]>
instead ofdynamic
, also in your PersonData classname
andage
must be properties, so it would look likebut I would recommend writing it like this for cleaner code
So the final request would look like
Hopefully this code will help you.
Tested post method like below
enter image description here