-2

I can't get System.Text.Json deserialization to work.

    public class LoginResponse
    {
        public LoginResponse()
        {

        }

        [JsonPropertyName("token")]
        public string Token;
    }

Example response from webservice which I want to deserialize:

{"token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImdvZG90IiwiZXhwIjoxNjQ2MDExODU1LCJpYXQiOjE2NDYwMTE1NTV9.tNtSWreYQjVxTuIFtzXdEWDY5Tr9I2tBI5D8gSR8FUTBDdsFKifzkHbYAshwxplQJc9m7e-1BxT3iV2_pQ7Uhw"}

But responseBody.Token remains empty:

var responseBody = JsonSerializer.Deserialize<LoginResponse>(Encoding.UTF8.GetString(body));

Any Idea what I'm doing wrong?

stuartd
  • 70,509
  • 14
  • 132
  • 163
Sven
  • 141
  • 5

1 Answers1

0

By default, System.Text.Json doesn't support binding to fields. You could change Token in your model to a property:

[JsonPropertyName("token")]
public string Token { get; set; }

If you're using .NET 5 or above you could use [JsonInclude] attribute on public fields:

[JsonInclude]
[JsonPropertyName("token")]
public string Token;
haldo
  • 14,512
  • 5
  • 46
  • 52