How To Convert Newtonsoft.Json.Linq.JArray To a List Of Object Type In C#


I'm making an HTTP POST request, sending HTML FormData to my ASP.NET Core API controller. The FormData contains one or more pieces of user data. How can I parse a List to a JArray using Newtonsoft.Json in C#? Essentially, we want to convert a Newtonsoft.Json.Linq.JArray to a list of a specific object type and let's discuess in this post.

Converting Newtonsoft.Json.Linq.JArray to a List of Product Objects

Let's assume we have a Product object with properties like Id, Name, Price, and Category. We want to convert a Newtonsoft.Json.Linq.JArray to a List of Product objects.

  1. Deserialize the JArray:

    First, we deserialize the JArray into a collection of JObject instances. We use Newtonsoft.Json's JsonConvert.DeserializeObject method for this.

    
    using Newtonsoft.Json.Linq;
    
    JArray jsonArray = JArray.Parse(jsonString);
    List<JObject> jObjectList = JsonConvert.DeserializeObject<List<JObject>>(jsonArray.ToString());
                
  2. Map JObject instances to Product objects:

    Next, we map each JObject instance to our Product object. We iterate over the collection of JObject instances using LINQ and convert each one to a Product object.

    
    using System.Collections.Generic;
    using System.Linq;
    
    List<Product> productList = jObjectList.Select(jObject =>
    {
        return new Product
        {
            Id = jObject["Id"].ToObject<int>(),
            Name = jObject["Name"].ToObject<string>(),
            Price = jObject["Price"].ToObject<decimal>(),
            Category = jObject["Category"].ToObject<string>()
        };
    }).ToList();
                


2
Let's assume we have an Employee object with properties like Id, Name, Department, and Salary. We want to convert a Newtonsoft.Json.Linq.JArray to a List of Employee objects using the array.ToObject<List<Employee>>() method.


Deserialize the JArray:

First, we deserialize the JArray into a List of Employee objects using the array.ToObject method.


using Newtonsoft.Json.Linq;

JArray jsonArray = JArray.Parse(jsonString);
List<Employee> employeeList = jsonArray.ToObject<List<Employee>>();
            

By following this step, we can efficiently convert a Newtonsoft.Json.Linq.JArray to a List of Employee objects in our C# code.

3 I have solved this by using the code below. Here is my JSON and the C# code for parsing it.
{
  "page_index": 3,
  "page_size": 20,
  "total_count": 50,
  "total_page_count": 3,
  "employees": [
    {
      "first_name": "John",
      "other_names": "Doe",
      "phone_number": "+1234567890",
      "gender": "Male",
      "client_status": "Active",
      "date_of_birth": "1985-03-20T00:00:00",
      "national_id": "123456789",
      "email_address": "[email protected]",
      "employee_id": 1,
      "added_date": "2022-01-15T00:00:00",
      "modified_date": "2022-02-10T00:00:00"
    },
    {
      "first_name": "Jane",
      "other_names": "Doe",
      "phone_number": "+9876543210",
      "gender": "Female",
      "client_status": "Inactive",
      "date_of_birth": "1990-07-12T00:00:00",
      "national_id": "987654321",
      "email_address": "[email protected]",
      "employee_id": 2,
      "added_date": "2021-11-20T00:00:00",
      "modified_date": "2022-03-05T00:00:00"
    }
  ],
  "has_previous_page": true,
  "has_next_page": true
}
The conversion of the items array to a list of clients was handled as follows:
if (responseMessage.IsSuccessStatusCode)
{
    var responseData = responseMessage.Content.ReadAsStringAsync().Result;
    JObject jsonResponse = JObject.Parse(responseData);

    var itemsArray = jsonResponse["items"].Value<JArray>();
    List<Client> clientList = itemsArray.ToObject<List<Client>>();

    return View(clientList);
}
4 Let's see converting a JArray to a generic List<> in C#?, Llet's consider an example of a PetsLover model with properties like Id, Name, PetName, and DOB and to convert a JArray to a generic List<> in C#, considering an example of a PetsLover model with properties Id, Name, PetName, and DOB, you can use the following approach:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

public class PetsLover
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PetName { get; set; }
    public DateTime DOB { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // Assuming jsonData is your JSON string containing the array
        string jsonData = @"[
            { 'Id': 1, 'Name': 'John', 'PetName': 'Max', 'DOB': '2015-05-20' },
            { 'Id': 2, 'Name': 'Alice', 'PetName': 'Buddy', 'DOB': '2018-09-10' }
        ]";

        // Parse the JSON string into a JArray
        JArray jsonArray = JArray.Parse(jsonData);

        // Convert the JArray to a list of PetsLover objects
        List<PetsLover> petsLoverList = jsonArray.ToObject<List<PetsLover>>();

        // Display the converted list
        foreach (var petsLover in petsLoverList)
        {
            Console.WriteLine($"Id: {petsLover.Id}, Name: {petsLover.Name}, Pet Name: {petsLover.PetName}, DOB: {petsLover.DOB}");
        }
    }
}

  • Here we define a PetsLover class with properties Id, Name, PetName, and DOB to represent the structure of the JSON objects and then using Newtonsoft.Json.Linq.JArray to parse the JSON string into a JArray and then use the ToObject<List<PetsLover>>() method to convert the JArray to a generic List<PetsLover>.
  • We iterate through the list and print out the properties of each PetsLover object.