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.


You need to grab the sample of the JSON content, then make a C# class using the 'Paste Special' option I described.

menu option

Then you can use the JsonConvert.DeserializeObject<T> (in a nuget package by Newtonsoft) to deserialize your web service response in a C# object instance.

Here are the C# classes I generated with your JSON object unaltered:

public class Rootobject
{
    public Result[] result { get; set; }
}

public class Result
{ 
    public string parent { get; set; }
    public string made_sla { get; set; }
    public string caused_by { get; set; }
    public string watch_list { get; set; }
    public string upon_reject { get; set; }
    public Resolved_By resolved_by { get; set; }
    public string approval_history { get; set; }
    public string number { get; set; }
}

public class Resolved_By
{
    public string link { get; set; }
    public string value { get; set; }
}

You use this type like this:

var json = "t-b-d"; // From Web Service call
Rootobject response = JsonConvert.DeserializeObject<Rootobject>(json);
// use the response object.

** UPDATED **

If you need a more flexible model, all JSON will deserialize into Dictionary<string, string>, but I have found that serialization / deserialization results are more reliable when the model is consistent

var response = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);

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());
    }
}