Web API中JWT认证场景下,如何从JSON反序列化获取token属性值?
Hey there, that JsonReaderException makes total sense—you're trying to deserialize a JSON object directly into a string, but the parser is seeing the opening { and panicking because it expects a quoted string instead. Let's fix this with a few straightforward approaches depending on which JSON library you're using.
First, let's confirm the structure of your JSON response (based on your description):
{ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" }
If you're using System.Text.Json (built-in for .NET Core/.NET 5+)
Option 1: Use a DTO Class (Type-Safe, Recommended)
Create a simple class that matches your JSON structure:
public class TokenResponse { // Map explicitly to the lowercase "token" key if needed [JsonPropertyName("token")] public string Token { get; set; } }
Then deserialize and extract the token:
using System.Text.Json; // Assume your raw JSON response is stored in jsonResponse var tokenResponse = JsonSerializer.Deserialize<TokenResponse>(jsonResponse); string jwtToken = tokenResponse.Token;
Option 2: Parse directly without a class
If you don't want to create a dedicated class, parse the JSON into a JsonDocument and pull the token value:
using System.Text.Json; using var jsonDoc = JsonDocument.Parse(jsonResponse); string jwtToken = jsonDoc.RootElement.GetProperty("token").GetString();
If you're using Newtonsoft.Json (Json.NET) (common for .NET Framework)
Option 1: DTO Class (Type-Safe)
Same idea, with Newtonsoft's attribute if needed:
public class TokenResponse { [JsonProperty("token")] // Optional if property name matches exactly (case-insensitive by default) public string Token { get; set; } }
Deserialize like this:
using Newtonsoft.Json; var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(jsonResponse); string jwtToken = tokenResponse.Token;
Option 2: Use JObject to extract directly
using Newtonsoft.Json.Linq; var jsonObject = JObject.Parse(jsonResponse); string jwtToken = jsonObject["token"].ToString();
Why you got the original error
Chances are you were trying to deserialize the entire JSON object directly into a string (like JsonSerializer.Deserialize<string>(jsonResponse)), but the parser expects a quoted string when deserializing to string—not an object starting with {. That's exactly what the error message is pointing out with "Unexpected character encountered while parsing value: {".
内容的提问来源于stack exchange,提问作者ProfK

