Search code examples
xamarin.androidjson.net

Sudden Death of dynamic JSON - newtonsoft.json.linq.jobject' does not contain a definition for


I am using a simple code to get the values from JSON

string JSON = ""; // MY JSON STRING
dynamic data = JObject.Parse(JSON);
Log.Info(TAG, "Access Token " + data.access_token);

This was working fine, I don't have any issue debugging but when I run it in production (Android Emulator) I get the error

newtonsoft.json.linq.jobject' does not contain a definition for "access_token"

My JSON String is the following

{
  "access_token": "tIl7bMlOAWJCtdAWKTylZQbo",
  "token_type": "bearer"
}

What I want to know is, why this just started happening where it always worked previously for the last 2 years and doesn't show any errors when debugging either?


Solution

  • The LINQ-to-JSON API (JObject, JToken, etc.) exists to allow working with JSON without needing to know its structure ahead of time. You can deserialize any arbitrary JSON using JObject.Parse like the code below. The JObject class can take a string indexer, just like a dictionary.

    string JSON = @"{'access_token': 'tIl7bMlOAWJCtdAWKTylZQbo', 'token_type': 'bearer'}"; // MY JSON STRING
            var data = JObject.Parse(JSON);
            var s = data["access_token"];
    

    JsonConvert.DeserializeObject, on the other hand, is mainly intended to be used when you know the structure of the JSON and you want to deserialize into strongly typed classes.

     public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();
        }
    
        private void Button_Clicked(object sender, EventArgs e)
        {
            string JSON = @"{
      'access_token': 'tIl7bMlOAWJCtdAWKTylZQbo',
      'token_type': 'bearer'
    }"; // MY JSON STRING          
    
    
            var jsondata = JsonConvert.DeserializeObject<MyTokenModel>(JSON);
            var ss = jsondata.access_token;
        }
    }
    
    public class MyTokenModel
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
    }
    

    Screenshot:

    enter image description here