A
A
Andrey2020-12-06 19:50:37
ASP.NET
Andrey, 2020-12-06 19:50:37

Why is json not being deserialized?

Good evening!

Can you please tell me why json is not being deserialized?
I use using System.Text.Json;
When accessing the api from Postman, I get the response:

{
    "id": 1,
    "number": 20000004,
    "bagGUID": null
}


public class Barcode
    {       
        public long Id { get; set; }

        public long Number { get; set; }

#nullable enable
        public string? BagGUID { get; set; }
       
    }


But for some reason, I can't deserialize the response :(
5fcd0a1270ae0321587740.png

What's wrong? There are no errors.

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2020-12-06
@andrey71

I tried running your code on mine. I have the same behaviour.
Apparently, by default, System.Text.Json does not apply any automatic name conversions.
Specified JsonPropertyName and everything worked.

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

var json = "{\"id\":1,\"number\":42,\"bagGUID\":null}";
var data = JsonSerializer.Deserialize<Barcode>(json);
Console.WriteLine(data!.ToString()); // выведет "Barcode { Id = 1, Number = 42, BagGuid =  }"

record Barcode
{
    [JsonPropertyName("id")]
    public int Id { get; init; }
    [JsonPropertyName("number")]
    public int Number { get; init; }
    [JsonPropertyName("bagGUID")]
    public Guid? BagGuid { get; init; }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question