ProfK
ProfK

Reputation: 51084

How do I deserialize only a property value from a JSON string?

I'm experimenting with JWT auth in a Web API project, and this is the code that fetches the token:

public static async Task Main(string[] args)
{
    var login = new {username = "mario", password = "secret"};
    var content = new StringContent(JsonConvert.SerializeObject(login), Encoding.UTF8, "application/json");
    var resp = await _client.PostAsync("api/Token", content);
    var json = await resp.Content.ReadAsStringAsync();
}

Yet the end value of json looks something like:

{ "token":"eyJhbGciOiJIUz...AXRbztetz_WhI"}

I would like to do something like:

var token = JsonConvert.DeserializeObject<???>(json);

but when I use

JsonConvert.DeserializeObject<string>(json)

I get a JsonReaderException:

Unexpected character encountered while parsing value: {. Path '', line 1, position 1.

Now how do I deserialize that json to get the string value of the token property?

Upvotes: 0

Views: 4319

Answers (2)

John Wu
John Wu

Reputation: 52280

You can define an anonymous type to use as a template and read the properties like this:

using Newtonsoft.Json;

var input = @"{'token':'eyJhbGciOiJIUzAXRbztetz_WhI'}";
var template = new { token = string.Empty };
var result = JsonConvert.DeserializeAnonymousType(input, template);
Console.WriteLine(result.token);

Output:

eyJhbGciOiJIUzAXRbztetz_WhI

Upvotes: 1

Raouf Ben Hassine
Raouf Ben Hassine

Reputation: 181

You can do something like this :

var parsedJson = JObject.Parse(json);
var token = (string)parsedJson["token"];

or

class TokenJsonResult{
  public string token {get;set;}
}

var parsedJson = JsonConvert.DeserializeObject<TokenJsonResult>(json);
var token = parsedJson.token;

Upvotes: 4

Related Questions