Christer
Christer

Reputation: 3076

c# .net Json get Node

I am trying to get the title from works in the following Json text:

Json_Text.html

But I get error when using this code:

for (int i = 0; i < 4; i++)
{
    var Title = obj["works"][i]["title"] as JArray;

    myTextbox.Text += "\n" + Title.ToString();
}

The error is at myTextbox:

Object reference not set to an instance of an object.

What am I doing wrong?

I do get out all the information in "works" => "authors" if I use this:

var Title = obj["works"][i]["authors"] as JArray;

but that's not what I want.

Upvotes: 1

Views: 979

Answers (3)

James Hatton
James Hatton

Reputation: 696

You are trying to do:

var Title = obj["works"][i]["title"] as JArray;

where 'title' is not a JSON array.

Whereas:

var Title = obj["works"][i]["authors"] as JArray;

works, because if you look at your diagram, you can see that authors is an array, which you then put in to Title.

Title is then null, so you get your exception.

Upvotes: 0

Carlos Mu&#241;oz
Carlos Mu&#241;oz

Reputation: 17814

The problem is on type of the expression obj["works"][i]["title"]

I think it should be a string

var Title = obj["works"][i]["title"];
myTextbox.Text += "\n" + Title.ToString();

Upvotes: 1

BlargleMonster
BlargleMonster

Reputation: 1622

I'm not sure what JSON library you are using, but it looks like you are casting title to an array when it is simply a string. Authors seems to be an array on the page you linked.

Try something like:

for (int i = 0; i < 4; i++)
{
    var Title = obj["works"][i]["title"]; //without the cast

    myTextbox.Text += "\n" + Title.ToString();
}

Upvotes: 0

Related Questions