I want to get these values in the "order_product" field (order_id, model) into a for or foreach loop how can I do that?
I have shared the following lines as an example. there are many sublines like this
{
"orders":[
{
"order_product":[
{
"order_product_id":"2189",
"order_id":"1688",
"model":"IT.KZ.1933"
},
{
"order_product_id":"2190",
"order_id":"1688",
"model":"IT.KZ.1830"
}
],
"id":"1688",
"entegration":"Ticimax"
}
]
}
CodePudding user response:
In your VS IDE, create a new class, copy the JSON in your question to clipboard, then Edit -> Paste Special -> Paste JSON as classes. The VS will generate classes automatically.
Then using JsonSerializer you could deserialize your JSON data as shown below, and can iterate over the order_product and its values using foreach.
string ordJson = File.ReadAllText(@"C:\myData\orders.json");
OrdersColl myOrders = JsonSerializer.Deserialize<OrdersColl>(ordJson);
foreach (Order myorder in myOrders.orders)
{
foreach( Order_Product order_Prod in myorder.order_product)
{
Console.WriteLine($"Model : {order_Prod.model} , order id :
{order_Prod.order_product_id}");
}
}
The below are the classes generated by the VS IDE based on the JSON that you gave in your question..
public class OrdersColl
{
public Order[] orders { get; set; }
}
public class Order
{
public Order_Product[] order_product { get; set; }
public string id { get; set; }
public string entegration { get; set; }
}
public class Order_Product
{
public string order_product_id { get; set; }
public string order_id { get; set; }
public string model { get; set; }
}
CodePudding user response:
First of all, if you want to use c# language constructions, you should deserialize your json to c# object using some json deserializer (e.g. System.Text.Json.JsonSerializer). In order to do this, you would need to create a model that corresponds json fields. Those steps are described in Microsoft Docs: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0 .
In your case your c# model will contain an array or a list of orders. Each order will contain an array called order_product. Then you would be able to use foreach loop on that array or any other data structure that is supported by your json deserializer and that contain GetEnumerator() method.
