我想將“order_product”欄位(order_id,model)中的這些值放入for或foreach回圈中,我該怎么做?
我分享了以下幾行作為示例。有很多這樣的子線
{
"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"
}
]
}
uj5u.com熱心網友回復:
在你的 VS IDE 中,創建一個新類,將問題中的 JSON 復制到剪貼板,然后 Edit -> Paste Special -> Paste JSON as classes。VS 會自動生成類。然后使用JsonSerializer您可以反序列化您的 JSON 資料,如下所示,并且可以order_product使用 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}");
}
}
以下是 VS IDE 根據您在問題中提供的 JSON 生成的類。
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; }
}
uj5u.com熱心網友回復:
首先,如果您想使用 c# 語言結構,您應該使用一些 json 反序列化器(例如 System.Text.Json.JsonSerializer)將您的 json 反序列化為 c# 物件。為此,您需要創建一個對應于 json 欄位的模型。這些步驟在 Microsoft Docs 中有描述:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0。
在您的情況下,您的 c# 模型將包含一個陣列或一個訂單串列。每個訂單將包含一個名為 order_product 的陣列。然后,您將能夠在該陣列或任何其他資料結構上使用 foreach 回圈,這些資料結構由您的 json 反序列化器支持并包含 GetEnumerator() 方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404609.html
標籤:
上一篇:FlutterAPI如何使用http插件從這個JSON中的設備獲取資料
下一篇:如何限制for回圈的迭代次數
