Ray Suelzer
Ray Suelzer

Reputation: 4107

NullReferenceException on ForEach JSON c#

I am having a problem with the following code. It uses the Facebook c# SDK. The problem is that I am pulling and printing a list of all of my friends work history. However, when this data isn't available I think it is causing a NullReferenceException. I have looked at a bunch of solutions online, but haven't found one that seems to work. Any help would be appreciated.

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var accessToken = "...";
        var client = new FacebookClient(accessToken);
        dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });

        foreach (dynamic friend in myInfo)
        {
            foreach (dynamic work in myInfo.work) // <---- here
            {
                Response.Write("Employer: " + work.employer.name + "<br/> Position:" + work.position.name + "<br/><br/>");
            }
        }
    }
}

I have included the suggested edits but am now getting a different error:

    namespace WebApplication1.Site
 {
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


        var accessToken = "xxx";
        var client = new FacebookClient(accessToken);
        dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });

        foreach (dynamic friend in myInfo)
        {
            **foreach (dynamic work in friend.work ?? new[] { new { employer = new { name = string.Empty }, position = new { name = string.Empty } } })**
                {
                    Response.Write("Employer: " + myInfo.work.employer.name);
                }

        }


    }
}
}

'System.Collections.Generic.KeyValuePair' does not contain a definition for 'work' on Line 21

Upvotes: 1

Views: 683

Answers (3)

dmck
dmck

Reputation: 7861

You can provide an empty list to inplace of the null value to avoid the null reference exception:

 foreach (dynamic work in friend.work ?? new List<string>())

You are getting the exception because foreach makes a call to .GetEnumerator() on a null value. I used a new List, but it doesn't really matter what is put here.. as long as it isn't null and it is enumerable.

Edit

You could provide an anonymous type that provides the properties you need:

 foreach (dynamic work in friend.work ?? new [] { new { employer = new { name = string.Empty}, position = new { name = string.Empty }}})

Upvotes: 1

Seth Flowers
Seth Flowers

Reputation: 9180

I'm not familiar with the API, but I'm guessing in your inner loop you probably mean to be iterating over a property of the object created in the outer loop.

For example:

foreach (dynamic friend in myInfo)
{
    foreach (dynamic work in friend.work) // rather than myInfo.work
    {
        // ...
    }
}

You should also probably have a null check around your inner loop, to guard against null reference exceptions.

Upvotes: 0

competent_tech
competent_tech

Reputation: 44941

Just test myInfo.work for null before starting the inner loop:

if (myInfo.work != null) {
   foreach (dynamic work in myInfo.work)

Also, I just noticed you may be using the wrong object:

if (friend.work != null) {
   foreach (dynamic work in friend.work)

Upvotes: 0

Related Questions