Deserializing nested json data

It's not entirely straightforward to deserialize the following data

{"data":{"app_id":"1611732946568","type":"USER","application":"DominanceAR","data_access_expires_at":1520915983,"expires_at":1565446700,"is_valid":true,"scopes":["email","public_profile"],"user_id":"10154545630145454537"}}


The problem is - it's one level nested down. You can also adopt a similar structure in your class models but it's pretty useless to do that. So, what's an alternative? Following four lines:

 

var content = await response.Content.ReadAsStringAsync();
JObject parent = JObject.Parse(content); 
var root = parent.Value<JObject>("data"); 
var fbToken = JsonConvert.DeserializeObject<FbToken>(root.ToString());


JObject.Parse from Newtonsoft comes to rescue. 

We specify the parent\shell node like this - parent.Value<JObject>("data"). It helps in getting past the enclosure.

Here is FbToken class -

public class FbToken
{ 
[JsonProperty("app_id")]
public string AppId { get; set; }

[JsonProperty("type")]
public string Type { get; set; }

[JsonProperty("application")]
public string Application { get; set; }

[JsonProperty("data_access_expires_at")]
public long ExpiresAt { get; set; }

[JsonProperty("is_valid")]
public bool IsValid { get; set; }

[JsonProperty("scopes")]
public string[] Scopes { get; set; }

[JsonProperty("user_id")]
public String UserId { get; set; }

}


Happy Deserializing.

 

 

Reference -

https://buildplease.com/pages/json/

 

Add comment