How to Convert JSON Array to JSON Object in .NET C#?

Convert JSON Array to JSON Object using the .NET C#. This is helpful in parsing the API response that comes as a JSON Array. You can get the value using the keys.

Below is the sample JSON Array example with 2 JSON Objects in it.

[
  {
    "name": "JD Bots",
    "email": "info@jd-bots.com"
  },
  {
    "name": "Dewiride Creations",
    "email": "info@dewiride.com"
  }
]

In some cases, there will be only a single JSON object returned from the API response. The code we will write will handle any scenario having 1 object or multiple objects.

For demo purposes, I am hardcoding the JSON array in a string variable.

string jsonResponse = "[{\"name\": \"JD Bots\",\"email\": \"info@jd-bots.com\"},{\"name\": \"Dewiride Creations\",\"email\": \"info@dewiride.com\"}]";

Install the NuGet package Newtonsoft.Json.

Install the Nuget package Newtonsoft.Json

Below is the complete code that will parse the JSON Array and iterate over all the JSON objects in the array and get the name and email values using the key.

using Newtonsoft.Json.Linq;
using System;

namespace JSONArrayToObject
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string jsonResponse = "[{\"name\": \"JD Bots\",\"email\": \"info@jd-bots.com\"},{\"name\": \"Dewiride Creations\",\"email\": \"info@dewiride.com\"}]";

            JArray jArray = JArray.Parse(jsonResponse);

            foreach (JObject jObject in jArray)
            {
                Console.WriteLine($"{(string)jObject["name"]} -> {(string)jObject["email"]}");
            }
        }
    }
}

Output Console

output console showing the parsed JSON array and json object in .net c#

Thank you All!!! Hope you find this useful.


Leave a Reply

Up ↑

%d