How to Parse a JSON with C#
Let a JSON be:
{
"access_token": "2564231sdfsdf1sd",
"expires_in": 3600,
"token_type": "Bearer"
}
There are at least two ways I know to access to the values with C#:
- With the Deserialization way
- With the JSON PAth Query way
Both of them requires you to install and reference
https://www.newtonsoft.com/json
The Deserialization way
With this method, you have to define a class that match the JSON and then perform the deserialisation:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
// You probably need more
namespace SSFS
{
public class Token{
public string access_token {get; set;}
public int expires_in {get; set;}
public string token_type {get; set;}
}
public class Utils {
string jsonString = @"{
"access_token": "2564231sdfsdf1sd",
"expires_in": 3600,
"token_type": "Bearer"}";
string getTokenValue(){
Token j = JsonConvert.DeserializeObject(jsonString);
return j.access_token;
}
}
}
JSON PAth Query way
With this method, you have to parse the JSON then perform the Query
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
// You probably need more
namespace SSFS
{
public class Utils {
string jsonString = @"{
"access_token": "2564231sdfsdf1sd",
"expires_in": 3600,
"token_type": "Bearer"}";
string getTokenValue(){
JObject o = JObject.Parse(jsonString);
string accessToken = (string)o.SelectToken("access_token");
return accessToken;
}
}
}