我正在為購物車使用 api,該購物車具有一些復雜的 json(對我來說非常復雜)資料,其結構如下面的螢屏截圖所示。在我的代碼中的這種情況下,我試圖修復一個錯誤,我將通過說明資料及其結構來解釋它,因為我對 JSON 和陣列非常陌生。

這是來自屬于客戶所下訂單的資料的 Visual Studio json 讀取器。[0] 索引處的此項具有一個customFields,其值為。
當客戶完成購買時,他們購買的某些商品可以具有自定義欄位,例如襯衫的尺寸(大)或(中)或(小)等......在 JSON 中,這些 customFields 有一個值,在這種情況下是我在感謝頁面上顯示的襯衫尺寸,以便客戶知道他購買的尺寸。本質上,我試圖讓資料準備好傳遞給感謝頁面視圖。
當我在控制器中呼叫這些專案時,代碼僅在購買的所有專案都具有customFields 時才有效。如果客戶購買了沒有自定義欄位的咖啡杯之類的東西,那么應用程式就會中斷,因為我猜我的代碼只考慮了實際具有customFields的專案。
這是我目前擁有的代碼,僅在購買的所有商品都有自定義欄位時才有效。這是在我的控制器內部。
public ActionResult Thankyou(string token)
{
int itemsCountAddedToCart = (int)obj["items"].Count();
var items = obj["items"].Select(o =>
new Item
{
name = o["name"].ToString(),
quantity = int.Parse(o["quantity"].ToString()),
price = double.Parse(o["price"].ToString()),
image = o["image"].ToString(),
url = o["url"].ToString(),
//This customFields is what works, but only if all items had custom fields.
customFields = o["customFields"][0]["value"].ToString(),
});
thankYouViewModel.OrderItems = items;
}
//ThankYou View Model that loads hold the data to be able to show in the view.
public class ThankYouViewModel
{
public IEnumerable<Item> OrderItems { get; set; }
}
public class Item
{
public string name { get; set; }
public double price { get; set; }
public int quantity { get; set; }
public string image { get; set; }
public string url { get; set; }
//customFields
public string customFields { get; set; }
}
所以上面的代碼可以作業,但是當我有沒有customFields 的專案時會中斷。這是我得到的錯誤:
System.ArgumentOutOfRangeException: '索引超出范圍。必須是非負數且小于集合的大小。引數名稱:索引'

那么我的代碼應該如何查看它當前的中斷位置,以便它可以解釋 JSON 中的一個專案沒有 customFields 屬性的情況?我非常卡住并嘗試添加一些條件陳述句但沒有奏效,因為我正在處理一些我不太了解的復雜 json。
uj5u.com熱心網友回復:
如果您想忘記 customFields 陣列中存在多個元素的可能性,并且只將第一個元素值轉換為字串,請使用以下命令:
customFields = (o["customFields"] == null || o["customFields"].Count() == 0)?null:o["customFields"][0]["value"].ToString(),
uj5u.com熱心網友回復:
customFields = o["customFields"][0]["value"].ToString(),您可以直接從 customFields 陣列中接收值。如果您的情況下沒有陣列,那么就沒有什么可得到的了。
我建議您檢查您的 customFields 是否存在:
var item = new Item ();
item.name = o["name"].ToString();
item.quantity = int.Parse(o["quantity"].ToString());
item.price = double.Parse(o["price"].ToString());
item.image = o["image"].ToString();
item.url = o["image"].ToString();
if(o["customFields"] != null)
{
item.customFields = o["customFields"][0]["value"].ToString();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/431509.html
標籤:C# 数组 json asp.net-mvc 条件语句
上一篇:SQL被當成代碼?谷歌的理由絕了
