9

I am using the guardian API to try and retrieve stories but keep receiving an exception. The string of json contains the below json, however I can't access the body using LINQ.

Here it is:

{
    "response":{
    "status":"ok",
    "userTier":"approved",
    "total":1,
    "startIndex":1,
    "pageSize":10,
    "currentPage":1,
    "pages":1,
    "orderBy":"newest",
    "results":[{
      "id":"sustainable-business/sustainable-finance-where-next-open-thread",
      "sectionId":"sustainable-business",
      "sectionName":"Guardian Sustainable Business",
      "webPublicationDate":"2014-02-13T13:27:00Z",
      "webTitle":"Where next for sustainable finance? - open thread",
      "webUrl":"http://www.theguardian.com/sustainable-business/sustainable-finance-where-next-open-thread",
      "apiUrl":"http://content.guardianapis.com/sustainable-business/sustainable-finance-where-next-open-thread",
      "fields":{
        "body":"<img src=\"http://hits.theguardian.com/b/ss/guardiangu-api/1/H.20.3/98867?ns=guardian&amp;pageName=Where+next+for+sustainable+finance%3F+-+open+thread+Article+2043222&amp;ch=Guardian+Sustainable+Business&amp;c2=461773&amp;c4=MIC%3A+Finance+%28GSB%29%2CMIC%3A+Guardian+Sustainable+Business%2CPRO%3A+Sustainability+%28Guardian+Professional%29&amp;c3=theguardian.com&amp;c6=Laura+Paddison&amp;c7=14-Feb-13&amp;c8=2043222&amp;c9=Article\" width=\"1\" height=\"1\" />..."
      }
     }]
     }
}

I have tried every thing including this:

string story = (string)ja["response"]["results"]["fields"]["body"];

Update:

public partial class Story : PhoneApplicationPage
{
    string url;
    string jsonData;

    // Http used so the json can be retrived via the get async methods
    HttpClient webClient = new HttpClient();

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (NavigationContext.QueryString.ContainsKey("key"))
        {
            string encodedValue = NavigationContext.QueryString["key"];
            url = Uri.UnescapeDataString(encodedValue);
            textBox.Text = url;
            guardianPanorama();
        }
    }
    private async void guardianPanorama()
    {
        try
        {
            HttpResponseMessage Result = await webClient.GetAsync(url);

            // This takes the http response content and is turned into a string
            jsonData = await Result.Content.ReadAsStringAsync();
           
            JObject ja = JObject.Parse(jsonData);

            // This takes the current bitcoin price and formats it so there is the      correct amount of decimal places
            string story = (string)ja["response"]["results"]["fields"]["body"];

            // It then gets added to the textbox
            textBox.Text = story;
        }
        catch (Exception errors)
        {
            MessageBox.Show("There has been a error with the Guardian API");
            Console.WriteLine("An error occured:" + errors);
        }
    }
}

Exception:

System.ArgumentException: Accessed JArray values with invalid key value: "fields". Array position index expected.

at Newtonsoft.Json.Linq.JArray.get_Item(Object key)

4
  • Can you post the code of how you retrieve the 'ja' JSON object? Commented Feb 17, 2014 at 3:37
  • 1
    and also if you post the exception. Thx Commented Feb 17, 2014 at 3:52
  • Perhaps that should be string story = (string)ja["response"]["results"][0]["fields"]["body"];? results is an array... Commented Feb 17, 2014 at 4:05
  • You are a star mate! How do I +1 your account? Commented Feb 17, 2014 at 4:09

1 Answer 1

28

If you replace

// This takes the current bitcoin price and formats it so there is the correct amount of decimal places
string story = (string)ja["response"]["results"]["fields"]["body"];

with

// This takes the current bitcoin price and formats it so there is the correct amount of decimal places
string story = (string)ja["response"]["results"][0]["fields"]["body"];

that should work for your example. Note the square bracket after results in the example you provided, that indicates an array that should be accounted for in your access code.

Sign up to request clarification or add additional context in comments.

5 Comments

What if the 1st response is in array form and the 2nd response is not in array form. Is there any way that I can know if the response is in array form or not?
@NickKing I think you can simply check the type of your JToken and check if It's an JArray or not.
I agree but I have a complex json and I want to know the type of the innermost json object of my json. For example, in this question's json I want to check if the "result" object (which is inside "response") is list or not.
@NickKing so you have to check the innermost object type then. Not sure what your problem is. Perhaps, you'd like to write up a new question fully describing your problem.
I wasn't sure if I can still check the innermost object type using JToken. But I did a quick test and I can check if the innermost object is an array or not. Thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.