Derek
Derek

Reputation: 367

Parsing Nested JSON in C#

Hi Guys this is the source JASON:

{
"is_error":0,
"undefined_fields":["custom"],
"version":3,
"count":1,
"id":15862,
"values":{
    "15862":{
        "id":15862,
        "contact_type":"Individual",
        "contact_sub_type":null,
        "do_not_email":null,
        "do_not_phone":null,
        "do_not_mail":null,
        "do_not_sms":null,
        "do_not_trade":null,
        "is_opt_out":null,
        "legal_identifier":null,
        "external_identifier":null,
        "sort_name":"last, first",
        "display_name":"first last",
        "nick_name":null,
        "legal_name":null,
        "image_URL":null,
        "preferred_communication_method":null,
        "preferred_language":"en_US",
        "preferred_mail_format":null,
        "hash":"2b",
        "api_key":"eb",
        "first_name":"Frist",
        "middle_name":"A.",
        "last_name":"Last",
        "prefix_id":null,
        "suffix_id":null,
        "email_greeting_id":null,
        "email_greeting_custom":null,
        "email_greeting_display":null,
        "postal_greeting_id":null,
        "postal_greeting_custom":null,
        "postal_greeting_display":null,
        "addressee_id":null,
        "addressee_custom":null,
        "addressee_display":null,
        "job_title":"Title",
        "gender_id":null,
        "birth_date":null,
        "is_deceased":null,
        "deceased_date":null,
        "household_name":null,
        "primary_contact_id":null,
        "organization_name":"OrgName",
        "sic_code":null,
        "user_unique_id":null
    }
}

}

I am having two problems. As you can see the numerical key under "values" is defined each time a response is returned, second, I cannot seem to gain access to anything inside the "values" key.

I have attemped to use JSON.Net but I am getting:

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.

When using:

JObject o = JObject.Parse(json);
JArray values = (JArray)o["values"];

to get to the innermost data (which is all I care about), but everything I attempt in order to get past the root level of the response doesn't work... Do you have any ideas?

Upvotes: 2

Views: 2734

Answers (1)

imichaelmiers
imichaelmiers

Reputation: 3509

just a thought, but try var f =o["values"] and see what that throws back. Its possible that that JArray is not what we assume it is.

Try using JavaScriptSerializer instead.

Upvotes: 2

Related Questions