Allison Paiva
Allison Paiva

Reputation: 37

How to access the values from a JArray?

My JArray is in the following format:

jArray = {"data": [
  {
    "Id": 29288,
    "SourceURL": "hhfythhs\\fg\d$",
    "TargetURL": "[email protected]",
    "Site_Owner_Email_IDs": "[email protected]",
    "siteId": null
  },
  {
    "Id": 30724,
    "SourceURL": "\\\\jnjphmafps1\\home$\\nriver46",
    "TargetURL": "[email protected]",
    "Site_Owner_Email_IDs": "[email protected], [email protected]",
    "siteId": null
  }
]}

I'm trying to access the Site_Owner_Email_IDs value with the following code:

foreach (var item in jArray)
{
    emailIDsoe = (string)item.Value["data"][0]["Site_Owner_Email_IDs"];
}

which is giving me an error:

Accessed JArray values with invalid key value: "data". Int32 array index expected.

How can I access the key Site_Owner_Email_IDs and its value for each item in jArray?

Upvotes: 1

Views: 1120

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129827

Your jArray is actually a JObject which contains a JArray (in the data property).

Try it like this:

foreach (var item in jArray["data"])
{
    emailIDsoe = (string)item["Site_Owner_Email_IDs"];
}

Fiddle: https://dotnetfiddle.net/tzcXql

Upvotes: 2

Related Questions