1

I'm newbie to using the dynamic keyword in C#. It seems simple enough, but I can't seem to use it effectively.

I see this example from Facebook:

var client = new FacebookClient();
dynamic me = client.Get("totten");
string firstname = me.first_name;

it works fine, but if you look at me in a debugger, then you can see that client.Get() returns simple JSON. The same it's said in Facebook documentation:

The result of this request is a dynamic object containing various properties such as first_name, last_name, user name, etc. You can see the values of this request by browsing to http://graph.facebook.com/totten in your web browser. The JSON result is shown below.

I want to do the same dodge with returned JSON from Foursquare:

private static string GetReturnedUrlFromHttp(string url)
{
    HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
    webRequest.Timeout = 10000;
    webRequest.Method = "GET";
    WebResponse response = webRequest.GetResponse();

    string responseStr = String.Empty;

    using (var stream = response.GetResponseStream())
    {
        var r = new StreamReader(stream);
        responseStr = r.ReadToEnd();
    }

    return responseStr;
}

public static void FillDataFromFoursquareUsingDynamic()
{
    string foursquare_url_detail = "https://api.foursquare.com/v2/venues/4b80718df964a520e57230e3?locale=en&client_id=XXX&client_secret=YYY&v=10102013";
    dynamic responseStr = GetReturnedUrlFromHttp(foursquare_url_detail);
    var response = responseStr.response;
}

I got the following error:

'string' does not contain a definition for 'response'

Why am I getting this error and is it possible to 'parse' any JSON string like in Facebook?

0

1 Answer 1

6

FacebookClient.Get doesn't really return the JSON string. Instead it parses the string into a dynamic object with properties matching the names of the values in the JSON string.

Using dynamic doesn't magically turn a string into an object with the properties defined in the string. Instead, you need to first parse the string with the help of a JSON library like JSON.NET.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.