'Object naming for JSON response with no JSON property name

I am connecting to an API, which returns json in the format:

[
  {
    "id":3810,
    "name":"productName",
    "slug":"",
    "permalink":"",
    "date_created":"2022-03-18T14:10:09",
    .
    .
    .

I have set up my root object as:

    public sealed class ProductRoot
    {
        public List<ProductItem> Products { get; set; }
    }

And my ProductItem class as:

    public sealed class ProductItem
    {
        [JsonPropertyName("id")]
        public long? Id { get; set; }

        [JsonPropertyName("name")]
        public string? Name { get; set; }

        [JsonPropertyName("slug")]
        public string? Slug { get; set; }

        [JsonPropertyName("permalink")]
        public string? Permalink { get; set; }

        [JsonPropertyName("date_created")]
        public DateTime? DateCreated { get; set; }

        ...

When I try to deserialize the response it seems to be failing at root.

ProductRoot = JsonSerializer.Deserialize<ProductRoot>(result);

Error:

System.Text.Json.JsonException: 'The JSON value could not be converted to Api.Entities.ProductRoot. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'

Question: If there is no json property to enter the JSON and it is just returning a set/list/array of items, does it matter what you call your root object? Does that impact how the json gets deserialized? Does anyone know why the above would be failing if it is not conflict with the root object?



Solution 1:[1]

You should deserialize directly into List<ProductItem>.

Regards,

Solution 2:[2]

If your object is:

    public sealed class ProductRoot
    {
        public List<ProductItem> Products { get; set; }
    }

then your json should be like:

{
"Products": [
  {
    "id":3810,
    "name":"productName",
    "slug":"",
    "permalink":"",
    "date_created":"2022-03-18T14:10:09",
    .
    .
    .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VadimG
Solution 2 yueyinqiu