Home > Back-end >  How use "Var json = new" to create a known JSON ouput? (C#)
How use "Var json = new" to create a known JSON ouput? (C#)

Time:09-09

Working on a project and basing it off a 2 year old project. Essentially here is what I'm trying to do:

Previously someone converted this:

{
    "referenceType": "PRO",
    "referenceNumber": "99959689585"
}

Into this:

var  json = new
        {
            referenceType = "PRO",
            referenceNumber = pro_number
        };

And I'm trying to do the same thing with something more complicated:

{
  "trackingInfo": [
    {
      "trackingNumberInfo": {
        "trackingNumber": "9084953743"
      }
    }
  ],
  "includeDetailedScans": false
}

I'm working in UIPATH. Trying to write an input to reach that output from above. How would I format a nested JSON

CodePudding user response:

I'm just declaring this in steps, starting from children to the root which is the requested object.


object trackingNumberInfo = new {
    trackingNumber = "9084953743"
};

object obj = new {
    trackingNumberInfo = trackingNumberInfo
};

object[] trackingInfo =
{
    obj
};

object json = new
{
    trackingInfo = trackingInfo
};

CodePudding user response:

All in one line:

var myJson = new
{
    trackingInfo = new[]
    {
        new
        {
            trackingNumberInfo = new
            {
                trackingNumber = "9084953743"
            }
        }
    },
    includeDetailedScans = false
};

It creates an anonymous object that contains an array of anonymous objects and another property.

Converting it to JSON:

var asJson = JsonConvert.SerializeObject(myJson);

Yields:

{
  "trackingInfo": [
    {
      "trackingNumberInfo": {
        "trackingNumber": "9084953743"
      }
    }
  ],
  "includeDetailedScans": false
}
  • Related