-1

Okay so I'm writing a windows form application that gathers data from a web sites html source code.

It needs to grab the gender of the person, but some people do not have a gender set so the gender doesn't show in the source code so it's throwing me an error.

What I'm wanting to do instead is if source code does not contain "gender" then Console.Write = "N/A".

Here is the code I currently have / am using to capture the data for gender.

JObject ob = JObject.Parse(html);
ob = JObject.Parse(html);
Console.WriteLine(html);
gt.gender = (string)ob["data"]["user"]["gender"];
Console.WriteLine(gt.gender);

I'm still kind of new to this so I'm wondering if there is some sort of if or else statement I could use there so it's not going to throw me an error in my application if the source code does not contain "gender".

Much appreciated.

Krunal Mevada
  • 1,637
  • 1
  • 17
  • 28
  • Which console? "I'm writing a windows form application" – spender Feb 13 '16 at 01:22
  • The Console.WriteLine just adds the data to a listview. It's a windows form application. – JohnDueDueDue Feb 13 '16 at 01:23
  • Read [this answer](http://stackoverflow.com/a/35329271/14357) I gave to another question. All will be clear. – spender Feb 13 '16 at 01:24
  • If I'm correct your answer only applies to if there is more than one instance in the source code but that's not what I'm trying to do. I'm grabbing the data "gender" which is m or f but sometimes this does not display and throws an error so what I want it to do if it doesn't display any gender is write "N/A" instead, – JohnDueDueDue Feb 13 '16 at 01:27
  • You might be looking for a dictionary class that will return a default value if given key is not found. Check the answers of [this](http://stackoverflow.com/questions/538729/is-there-an-idictionary-implementation-that-on-missing-key-returns-the-default) question for examples. – sithereal Feb 13 '16 at 01:37

1 Answers1

1

You can test for properties on a JObject as follows:

JObject item = //your JObject;
var hasFooProp = item.Properties().Any(p => p.Name == "foo");
if(hasFooProp)
{
    //item["foo"] is safe to read
}
else
{
    //set your N/A
}
spender
  • 117,338
  • 33
  • 229
  • 351