我在反序列化來自 API(.NET6,使用 System.Text.Json)的回應時遇到了新手問題。我使用這個成功地得到了回應:
var itemresponse = await response.Content.ReadFromJsonAsync<JSON_Item>();
我得到了“itemresponse”中預期的所有嵌套值,在 VS 除錯器中完全可見。現在我希望遍歷回應并提取相關值 - 看起來簡單明了......
首要問題:
我可以像這樣從第一級提取值:
string test1 = itemresponse.product.title;
但是,我無法從 Variant 中獲取嵌套值,如下所示:
string test2 = itemresponse.product.variants.sku;
“變體”中的所有屬性都是未知的,我不能在 Visual Studio 中“點”它們。
第二題:
我正在嘗試使用以下方法遍歷回應中的所有值:
foreach (var w in itemresponse.product)
{
string test = w.vendor; // Works
string test2 = w.variants.sku; // sku not recognizable
}
我知道我的“itemresponse”不是一個串列,但我希望無論如何都能遍歷該物件。嗶..不可能。我得到這個:“foreach 不能對“Product”型別的變數進行操作,因為“Product”不包含“GetEnumerator”的公共實體或擴展定義。
好的,我做了一些更改:
var itemresponse = await response.Content.ReadFromJsonAsync<List<JSON_Item>>();
foreach (var w in itemresponse)
{
string test = w.product.vendor; // Works
string test2 = w.product.variants.sku; // sku still not recognizable
}
嘗試運行時,我得到以下資訊:JsonException:無法將 JSON 值轉換為 System.Collections.Generic.List`1[Project.Models.JSON_Item]。路徑:$ | 行號:0 | 位元組位置內線:1。
我被卡住了,我不知道如何從“變體”中獲取嵌套值。請使用“最佳實踐”尋求幫助。
提前非常感謝。
勒內
以下是我使用的類:
public class JSON_Item
{
public Product product { get; set; }
}
public class Product
{
public long? id { get; set; }
public string title { get; set; }
public string body_html { get; set; }
public string vendor { get; set; }
public List<Variant> variants { get; set; }
}
public class Variant
{
public long? id { get; set; }
public long? product_id { get; set; }
public string? title { get; set; }
public string? price { get; set; }
public string? sku { get; set; }
}
回應 JSON 示例:
{
"product":{
"id":6912905806009,
"title":"This is the title",
"body_html":"Description here...",
"vendor":"Cronus Inc.",
"variants":[
{
"id":40775169605817,
"product_id":6912905806009,
"title":"Variant 1",
"price":"899.00",
"sku":"5710698076083"
}
]
}
}
編輯:嵌套 foreach 回圈之類的東西會持久嗎?
foreach (var q in itemresponse.product)
{
string title = q.product.title;
foreach (var w in itemresponse.product.variants)
{
string test = w.sku;
}
}
如果是這樣,我該如何連接回圈,以確保變體通過我的 JSON 物件鏈接到正確的產品回圈?
我想知道“最佳實踐”解決方案是什么?猜猜這是從嵌套 JSON 物件中提取值的常見需求?
uj5u.com熱心網友回復:
對于第一期(和第二期,但稍后會詳細介紹),您無法直接在變體串列中訪問 SKU。在您的示例中:
string test1 = itemresponse.product.title;
有效,因為標題是產品物件的屬性。
string test2 = itemresponse.product.variants.sku;
不起作用,因為變體串列沒有 SKU 屬性。您需要訪問變體串列中的特定變體物件以獲取 SKU。例如,您可以執行以下操作:
foreach (var variant in itemresponse.product.variants) {
Console.WriteLine(variant.sku);
}
對于第二個問題,在您的示例中,您將物件(專案回應和產品)視為串列并嘗試遍歷它們。這是無效的。您只能對可迭代的資料結構(例如串列或陣列)進行 foreach。如果您從這些代碼片段中洗掉 foreach,那么您將遇到與第一次相同的問題,即您嘗試從變體串列中訪問變體物件的屬性,這也是無效的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482424.html
上一篇:如何在按鍵時也激活可點擊按鈕?(Windows表單C#)
下一篇:將雙引號添加到串列以顯示在標簽中
