JSON 值无法转换为 Scraper.items[]

The JSON value could not be converted to Scraper.items[]

所以我试图将 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;

(我知道我没有做属性或任何构造函数。我在尝试解决我的问题时将它们全部删除了。(其他对象也在那里,但我不会展示它们,因为我认为它们不是制作的东西我的例外情况,我不希望这个 post 不可读))

我的JSON:https://pastebin.com/AZE1AwhL

感谢阅读本文,获得一些帮助会让我在项目上取得很大进步。

您链接的 JSON 不是数组。它是一个对象,带有一个 属性 items 这是一个数组。所以 JsonSerializer.Deserialize<items[]> 不会起作用。您需要使用 items 属性.

反序列化为 class

像这样:

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# 命名约定规定您应该对 class 名称使用 PascalCasing。所以 items 应该被称为 Items 或更恰当地 Item 因为它不是列表类型。