1

I'm trying to serialize this json structure in c# and was wondering how would I serialize the address array in my structure below without having to use classes

Heres the structure

{
    "Name":"Mark",
    "Addresses":[
      {
        "address":"1234 Main street",
      },
      {
        "address":"1234 Pine Street",
      }],
}

Here's how I serialize using a JsonSerializer and only serializing one address

 string jsonObject = JsonSerializer.Serialize(new
                    {
                        name = "Mark",
                        Addresses = new
                        {
                            address= "1234 Main street"
                        },
                    });

How can I serialize the other address

1
  • Addresses = new [] {new { address= "1234 Main street" }, new {.…}}, Commented Dec 7, 2021 at 15:39

1 Answer 1

3

You need to instantiate a collection type, such as an array:

string jsonObject = JsonSerializer.Serialize(new
{
    name = "Mark",
    Addresses = new[]
    {
        new { address = "1234 Main street" }
    },
});

Working Example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.