C# – How To Convert JSON Array To List?

  • Post author:
  • Post category:C#

Introduction

In today’s world most of the data is transmitted over the web, and we often rely on JSON files for this purpose however there is a common issue faced by a lot of developers more specifically those who use NewtonSoft’s JSON.NET library, When the JSON data they receive consists of a JArray.

Developers often don’t understand how can they convert the NewtonSoft.Json.Linq.JArray value to a List, but the solution is very simple, and we will discuss it below.

📌 Outline

  • What is JSON Array?
  • How To Convert JSON Array to List?

📌 Prerequisites

  • Basic knowledge of JSON notation
  • Minor working experience with NewtonSoft’s Json.NET library

What is JSON Array?

JArray is basically a JSON Array, and it consists of a List of Values for One Key in a .JSON file. For Example, in the following code snippet “allow_modules” is the Key and the other strings are an Array of Values, this is what JSON Array is.

  "allow_modules": [
    "Manufacturing",
    "Event Streaming",
    "pharmacy",
    "Payment Gateways",
    "Core",
    "CRM",
    "Projects",
    "Bulk Transaction",
    "Automation"
  ]

How To Convert JSON Array to List?

Now we will learn how to convert the JSON Array Value to List
Take a look at the following lines of code

âš¡ Problem

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace codegitz
{
    internal class Program
    {
        private static JArray GetArray()
        {
            JArray newArray = new();
            newArray.Add("Example 1");
            newArray.Add("Example 2");
            newArray.Add("Example 3");

            return newArray;
        }

        static void Main(string[] args)
        {
            // Dictionary to store data
            Dictionary<string, dynamic> KVP = new();
            
            // The array used for demonstration
            JArray jArray = GetArray();

            // Assign value to key
            KVP["ExampleKey"] = jArray;


            /*
             * Here we will take the value previously assigned to the key and assign it to a list of strings
             * But implicit conversion of JArray to List is forbidden hence an exception will be thrown
             */
            List<String> ExampleList = KVP["ExampleKey"];

        }
    }
}

Running the above code results in the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message=Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'System.Collections.Generic.List<string>'
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

🛠 Solution

Now that we know what the issue is, it is time to come up with the solution which is Explicit Type Casting
Take a look at the following lines of code

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace codegitz
{
    internal class Program
    {
        private static JArray GetArray()
        {
            JArray newArray = new();
            newArray.Add("Example 1");
            newArray.Add("Example 2");
            newArray.Add("Example 3");

            return newArray;
        }

        static void Main(string[] args)
        {
            // Dictionary to store data
            Dictionary<string, dynamic> KVP = new();
            
            // The array used for demonstration
            JArray jArray = GetArray();

            // Assign value to key
            KVP["ExampleKey"] = jArray;


            /*
             * Here we will take the value previously assigned to the key and assign it to a list of strings
             * But implicit conversion of JArray to List is forbidden hence an exception will be thrown
             */
            //List<String> ExampleList = KVP["ExampleKey"];


            // This is how we fix the error
            List<String> ExampleList = (List<String>)KVP["ExampleKey"].ToObject(typeof(List<String>));

            foreach(String example in ExampleList)
            {
                Console.WriteLine($"{example}\n");
            }
        }
    }
}

The output of the above code will be:

Example 1

Example 2

Example 3

And just like that, we got rid of the pesky error

🔷 Other Cases

For an Integer List

List<int> ExampleList = (List<int>)KVP["ExampleKey"].ToObject(typeof(List<int>));

For a Boolean List

List<bool> ExampleList = (List<bool>)KVP["ExampleKey"].ToObject(typeof(List<bool>));

Conclusion

Today we learned about JSON Array and why it is used, Furthermore we learned implicit conversion of JSON Array to List is forbidden, and then we tackled the problem by learning how to convert the JArray to a List with different examples.
All we have to do is Explicitly Cast the JSON Array to the desired List type.

To learn more about C# go Here