atoms
atoms

Reputation: 3093

Creating an array in C# that contains an object

I have a RequestModel that contains some properties and another class Consignment.

Calling JsonConvert.SerializeObject(this); returns

{ "consignment": { "collectionDetails": null } }

Instead I would like to return an array of the object

"consignment": [ { "collectionDetails": null } ]

I've tried to create Consignment[] but get a conversion issue.

I've also tried to create a List<Consignment>

class RequestModel
{
    public string job_id { get; set; }
    public Consignment consignment = new Consignment();

    public class Consignment
    {
        public string consignmentNumber { get; set;
    }

    public string ToJSON()
    {
        return JsonConvert.SerializeObject(this);
    }

Upvotes: 2

Views: 100

Answers (1)

Always Learning
Always Learning

Reputation: 2713

Here you go:

public class RequestModel
{
    public string job_id { get; set; }
    public Consignment consignment { get; set; }

    public RequestModel()
    {
        consignment = new Consignment();
    }                

    public string ToJSON()
    {
        return JsonConvert.SerializeObject(this);
    }
}

Then your Consignment DTO would look like this assuming you have a CollectionItems class (didn't see any code in question around this):

public class Consignment
{
    public List<CollectionItems> collectionDetails { get; set; }
    public Consignment()
    {
        collectionDetails = new List<Collection>();
    }
}

Upvotes: 2

Related Questions