所以我試圖將一個 JSON 字串轉換為我自己制作的物件串列,但由于某些原因,它不斷向我拋出錯誤,并且在谷歌搜索后我找不到我的錯誤。
這是引發錯誤的原因。(我已經嘗試使用串列而不是陣列,但它仍然出現例外)。
items[] items = JsonSerializer.Deserialize<items[]>(h.Content.ReadAsStringAsync().Result);
這是我得到的例外:
"The JSON value could not be converted to Scraper.items[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
這是我的物件項的樣子:
public Int64 id;
public string title;
public double price;
public string currency;
public string brand_title;
public string size_title;
public user user;
public bool is_for_swap;
public string url;
public bool promoted;
public photo photo;
public int favorit_count;
public bool is_favorite;
public string badge;
public string[] conversion;
public int view_count;
(我知道我沒有做屬性或任何建構式。我在嘗試解決我的問題時將它們全部洗掉。(其他物件也在那里,但我不會顯示它們,因為我不認為它們是使我例外的東西,我不不希望這篇文章不可讀))
我的 JSON:https ://pastebin.com/AZE1AwhL
感謝您閱讀本文并獲得一些幫助將使我的專案取得很大進展。
uj5u.com熱心網友回復:
您鏈接的 JSON 不是陣列。它是一個物件,其屬性items是一個陣列。所以JsonSerializer.Deserialize<items[]>行不通。您需要反序列化為具有items屬性的類。
像這樣的東西:
public class Wrapper
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
// ...
var options = new JsonSerializerOptions { IncludeFields = true };
var wrapper = JsonSerializer.Deserialize<Wrapper>(
h.Content.ReadAsStringAsync().Result,
options);
wrapper.Items // This is your array
旁注:C# 命名約定規定您應該使用 PascalCasing 作為類名。所以items應該被稱為Items或更恰當Item,因為它不是串列型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/427722.html
標籤:C# json 目的 网页抓取 system.text.json
上一篇:如何在使用router.Any和通配符處理請求后保留路徑引數
下一篇:美麗的湯-洗掉HTML標簽的麻煩
