Search code examples
c#jsonjson.netjson-deserialization

RuntimeBinderExeption when refering json object to string


I am using Newtonsoft.Json to deserialize my JSON. Here is my JSON string.

{
    "data": {
        "type": "records",
        "id": "7",
        "attributes": {
            "created": "2017-01-19T08:42:56Z",
            "updated": "2017-01-19T08:42:56Z",
            "state": 3,
            "data": {
                "Lastname": [
                    "Gonzales"
                ],
                "Firstname": [
                    "Lacy"
                ],
                "Email": [
                    "ludam@gmail.com"
                ],
                "Salutation": [
                    "Mrs."
                ]
            }
        }
    }
}

So when I create a dynamic variable like this and assign the firstname into string s I get a RuntimebinderException.

dynamic data = JsonConvert.DeserializeObject(responseString2);
string s = data.attributes.data.Firstname;

Is there something I forgot?


Solution

  • Judging by your JSON structure, Firstname is actually an array with a single item.

    Also, since your JSON contains a root object named data, it seems like you're missing that too (might be confusing since you named your variable data as well).

    I would go with:

    dynamic result = JsonConvert.DeserializeObject(responseString2);
    string s = result.data.attributes.data.Firstname[0];
    

    Obviously, if you're in control of the returned JSON, you may refactor it into something that is more easily consumed:

    "FirstName": "Lacy",
    

    Also, you can avoid dynamic altogether by accessing your data using raw JObject:

    var firstName = JObject.Parse(json).SelectToken("data.attributes.data.Firstname[0]").ToString();
    

    See LINQ to JSON for more options