2

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);
    }
3
  • 1
    Where does collectionDetails come from? all i see is consignmentNumber. Also, why does job_id not show up, are you sure you are reading the correct json? Commented Apr 6, 2018 at 16:23
  • 4
    "I've tried to create Consignment[] but get a conversion issue." perhaps show that code so we can help fix it Commented Apr 6, 2018 at 16:23
  • If you are using a List say called computerList of object Computer you need to use List<Computer> computerList = new List<Computer>(); and then add as so computerList.Add(new Computer(words[0], words[1], "N/a", words[2], words[3])); Commented Apr 6, 2018 at 16:28

1 Answer 1

2

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>();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

many thanks this would work great! I realised I could do it outside of the Consignment class too.

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.