Ali
Ali

Reputation: 2768

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?

Upvotes: 1

Views: 2239

Answers (2)

Aravindhan R
Aravindhan R

Reputation: 269

The creator of JSON.Net himself addressed it here

Assuring that it's something minor and the exception is by design.

By the way if you wish to disable these warnings just because they make you uncomfortable.

In Visual Studio click on Tools - > Options and then select Debugging and Check the box that says Enable Just My Code.

More Info Stackoverflow

Upvotes: 0

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10958

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

Upvotes: 1

Related Questions