Hello @Muhammad Ahmed
The best path is to deserialize to a list which allows you to have better control such as using a for/next or the ability to use linq to find information. Below shows using a class to read the data while the other uses a slight variation of what you presented. If these do not work for you let me know why/
Example using Newtonsoft.Json
Json (with minimal information)
[
{
"id": 1,
"customerId": 100
},
{
"id": 2,
"customerId": 234
},
{
"id": 3,
"customerId": 300
},
{
"id": 4,
"customerId": 234
}
]
Class to contain above data.
public class Order
{
public int id { get; set; }
public int customerId { get; set; }
}
Deserialize
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JsonSampleLibrary.Classes;
using Newtonsoft.Json;
namespace JsonSampleLibrary
{
public class DynamicOperations
{
public static List<Order> ReadOrdersStrongTyped(string fileName)
{
return JsonConvert.DeserializeObject<List<Order>>(File.ReadAllText(fileName));
}
}
}
Work with the deserialized data first traversing all then using lambda to get orders for a specific customer.
var ordersList = DynamicOperations.ReadOrdersStrongTyped("orders.json");
for (int index = 0; index < ordersList.Count; index++)
{
Console.WriteLine(ordersList[index].id);
}
Console.WriteLine();
var id = 234;
var specificOrder = ordersList.Where(order => order.customerId == id).ToList();
for (int index = 0; index < specificOrder.Count(); index++)
{
Console.WriteLine(specificOrder[index].id);
}
Then the other way is with no class similar to what you have.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JsonSampleLibrary.Classes;
using Newtonsoft.Json;
namespace JsonSampleLibrary
{
public class DynamicOperations
{
public static void ReadOrders1(string fileName)
{
var jsonString = File.ReadAllText(fileName);
var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach (var o in objects)
{
Console.WriteLine($"{o.id}");
}
}
}
}
In the above o.id is known as an integer e.g. testing the type
foreach (var o in objects)
{
JValue id = o.id;
Console.WriteLine($"{id.Type}");
}
And typing id column
public static void ReadOrders1A(string fileName)
{
var jsonString = File.ReadAllText(fileName);
var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);
List<int> identifiers = new List<int>();
foreach (var o in objects)
{
identifiers.Add(Convert.ToInt32(o.id));
}
}