Search code examples
c#.netdictionarydynamicjil

Check if Dictionary value is an array


I have a dictionary in my code which holds key value pairs from 3rd party API call. I get the API response as a serialize string. So I hold these values in a dictionary like below

var res = await APICall();
var bookingTypes = Jil.JSON.DeserializeDynamic(res)["Bookings"][0];
var bookingData = (IDictionary<string, object>)bookingTypes;

some of the properties in bookingTypes are an array. Sometimes these arrays are empty and because of that I get an error when I'm trying get the value of first element of that array

string test = bookingData.ContainsKey("OrderCodes") ? bookingTypes.OrderCodes?[0] : "";

In above case bookingTypes.OrderCodes is empty []. I cannot check for array length since it is a dynamic value. How can I overcome this issue?

UPDATE #1

Added API response

{
   "Bookings":[
      {
         "PersonalID":1025,
         "Name":"Brian K. Thomas",
         "OrderCodes":[
            
         ],
         "PrevOrders":[
            2390,
            3115
         ]
      }
   ]
}

UPDATE 2

When I try to get value from the dictionary this is what I get (immediate window). Please note that "PrveOrders" is another array like property but with values. Added it also you can compare it

bookingData.TryGetValue("PrveOrders", out object kws4);
true
kws4
{[239]}
    Dynamic View: Expanding the Dynamic View will get the dynamic members for the object
bookingData.TryGetValue("OrderCodes", out object kws5);
true
kws5
{[]}
    Dynamic View: Expanding the Dynamic View will get the dynamic members for the object

Solution

  • As the JIL documentation points out you could use

    • member access on objects
    • and .Length on arrays

    in case of dynamic deserialization.

    var json = "{\"Bookings\":[{\"PersonalID\":1025,\"Name\":\"Brian K. Thomas\",\"OrderCodes\":[],\"PrevOrders\":[2390, 3115]}]}";
    var semiParsed = Jil.JSON.DeserializeDynamic(json);
    
    var orderCodes = semiParsed.Bookings[0].OrderCodes;
    var orderCode = orderCodes.Length > 0 ? orderCodes[0] : "";
    Console.WriteLine(orderCode); //prints empty line
    
    var prevOrders = semiParsed.Bookings[0].PrevOrders;
    var prevOrder = prevOrders.Length > 0 ? prevOrders[0] : "";
    Console.WriteLine(prevOrder); //prints 2390
    

    Dotnet fiddle link: https://dotnetfiddle.net/2RFMVJ