Search code examples
c#jsonajaxasp.net-ajax

How to serialize list in JSON object


I have a serialised object

{
a: “test”,
B[1].Name : “test”,
B[1].Surname : “testing”,
Etc.

But when I sent this object in using ajax Post method in cshtml file, my model is setting the list of b to null

When I’m actual fact I am sending data, but not in the correct format for the controller to understand

How do I serialise the object even further to send the correct model to the controller like

{
a: “test”,
B: {{ Name : “test”,Surname : “testing”}}
Etc.

Solution

  • You typically serialize json by using a serialization library, for example System.Text.Json.

    To serialize a list, just create a list or array of your objects, and give it to the library for serialization

    public record MyClass(int Age, string  Name)
    ...
    var list = new List<MyClass>(){new (50, "Bilbo"), new (2931 , "Legolas") };
    var json = JsonSerializer.Serialize(list);
    
    

    Resulting in:

    [
    {"Age":50,"Name":"Bilbo"},
    {"Age":2931 ,"Name":"Legolas"}
    ]
    

    I.e. an Json array of objects.

    I'm not sure what your example is supposed to be, or how you created it, but it does not look like json.