3

I'm trying to get the token value from a JsonConvert.DeserializeObject

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

Value token:

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

I've tried to split the string but thats not the clean way is there a another way to solve this ?

Devbrah
  • 59
  • 1
  • 8
  • where you have tried to trim string ? show us code – SUNIL DHAPPADHULE May 28 '19 at 06:25
  • Is that even a valid JSON response with `{{` and without a `"` at the end of the token? Please give us correct information. – Thomas Weller May 28 '19 at 06:26
  • You're deserializing the string to an object, because JsonConvert doesn't know the type. You can either deserialize to a `dynamic` or use `JsonConvert.DeserializeObject` and use a model Class – MindSwipe May 28 '19 at 06:26

2 Answers2

1

Assuming this is the JSON you're getting (as the JSON in your question is invalid)

{
    "token":"eyJraWQiOiJNSytSKzRhYUk4YjBxVkhBMkZLZFN4Ykdpb3RXbTNXOGhZWE45dXF3K3YwPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIxYmRlZjJkNy05YTRlLTRmYmYtYTk4Zi02Y2EwNzE0NTgzNzgiLCJlbWFpb"
}

you can 1: Deserialize it to a dynamic like so: (as mentioned in this answer)

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

or (my preferred typesafe way) use a model class to deserialize to like so:

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);
}
MindSwipe
  • 7,193
  • 24
  • 47
-1

You can try this

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