Search code examples
c#jsonservicenowservicenow-rest-api

Access JSON keys in C# from ServiceNow Rest API


I am calling the ServiceNow Incidents table and pulling back one incident like this. https://mydevInstance.service-now.com/api/now/v1/table/incident?sysparm_limit=1

var client = new RestClient("https://mydevInstance.service-now.com/api/now/v1/table/incident?sysparm_limit=1");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic myAuthKey");
IRestResponse response = client.Execute(request);

The JSON it returns in RESTSharp looks like this.

{
    "result": [
        {
            "parent": "",
            "made_sla": "true",
            "caused_by": "",
            "watch_list": "",
            "upon_reject": "cancel",
            "resolved_by": {
                "link": "https://mydevInstance.service-now.com/api/now/v1/table/sys_user/5137153cc611227c000bbd1bd8cd2007",
                "value": "5137153cc611227c000bbd1bd8cd2007"
            },
            "approval_history": "",
            "number": "INC0000060"
        }
    ]
}

How do I create a C# list or array of all the Keys under result? I can't Serialize the object with JSON.Net because additional keys can be added over time.


Solution

  • Here is what does work using System.Text.Json

    var incidentFields = new List<string>();
    
    var doc = JsonDocument.Parse(json);
    foreach (var o in doc.RootElement.GetProperty("result").EnumerateArray())
    {
        foreach (var p in o.EnumerateObject())
        {
            incidentFields.Add(p.Name.ToString());
        }
    }