Search code examples
c#jsonangulartypescripthttp

Deserialize a JSON string containing multiple arrays of custom objects


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}]}"

EDIT - Solution Thanks to Joy's comment below, I was able to resolve this. In addition to their comment, I had to make the fields public, and use List<PersonData> array1 = (List<PersonData>)arr1.ToObject(typeof(List<PersonData>)); in order to turn each dynamic object into a List of PersonData objects.


Solution

  • 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