You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:10:14