如何从jsonconvert.deserializeobject获取令牌值

时间:2019-05-28 06:21:58

标签: c# json.net

我正在尝试从JsonConvert.DeserializeObject获取令牌值

   static async Task Main(string[] args)
    {
        var apiClient = new ApiClient("https://connect.creditsafe.com/v1/");
        var authenticate =  await Authenticate(apiClient);
        var token =JsonConvert.DeserializeObject(authenticate.RawContent.ReadAsStringAsync().Result);    
        Console.ReadKey();
    }

价值代币:

    {{
  "token": "eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb
}}

我尝试拆分字符串,但是那不是干净的方法,还有另一种解决方法吗?

3 个答案:

答案 0 :(得分:0)

假设这是您要获取的JSON(因为您问题中的JSON无效)

{
    "token":"eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb"
}

您可以1:将其反序列化为dynamic,如下所示:(如this答案中所述)

dynamic parsed = JObject.Parse(authenticate.RawContent.ReadAsStringAsync().Result)
Console.WriteLine(parsed.token);

或(我首选的类型安全方式)使用模型类进行反序列化,例如:

class AuthenticationModel
{
    [JsonProperty("token")]
    public string Token {get; set;}
}

static async Task Main(string[] args)
{
    var parsed = JsonConvert.DeserializeObject<AuthenticationModel>(await authenticate.RawContent.ReadAsStringAsync());
    Console.WriteLine(parsed.Token);
}

答案 1 :(得分:0)

我认为,如果您读取原始内容流,那么初始模型绑定尝试将抵消内容缓冲区,因此您只会得到部分字符串。尝试读取Content而不是Rawcontent

 token =JsonConvert.DeserializeObject(authenticate.Content.ReadAsStreamAsync().Result); 

答案 2 :(得分:-1)

您可以尝试

 dynamic obj =JsonConvert.DeserializeObject<dynamic>(authenticate.RawContent.ReadAsStringAsync().Result);
    string token = Convert.ToString(obj.token);