Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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 :

You should deserialize directly into List<ProductItem>.

Regards,

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading