skip to Main Content

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


  1. Could you provide the thrown error? I would suggest using
    var person1 = JsonSerializer.Deserialize<PersonData[]>(data.Array1); in your backend or perhaps var dict = JsonSerializer.Deserialize<Dictionary<string, PersonData[]>>(data); var person1 = dict["Array1"];

    Login or Signup to reply.
  2. You could use Dictionary<string, PersonData[]> instead of dynamic, also in your PersonData class name and age must be properties, so it would look like

    class PersonData {
        public string name { get; set; }
        public int age { get; set; }
    }
    

    but I would recommend writing it like this for cleaner code

    class PersonData {
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("age")]
        public int Age { get; set; }
    }
    

    So the final request would look like

    [HttpPost("/check-person-data")]
    public IActionResult CheckPersonData([FromBody]Dictionary<string, PersonData[]> data)
    {
        return Ok();
    }
    
    Login or Signup to reply.
  3. Hopefully this code will help you.

    public IActionResult postData([FromBody] dynamic data)
        {
            var dataOut = JsonConvert.DeserializeObject<dynamic>(data.ToString());
            var arr1 = dataOut.Array1;
            var arr2 = dataOut.Array2;
            return null;
        }
    

    Tested post method like below
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search