0

I have a C# console app fetching json from a web api. Using Newtonsoft JSON deserialization, I successfully manage to pull the data however I can't access data[0] for example.

My code:

internal class Program
{
    private static void Main()
    { // TODO: check if HttpWebRequest can replace WebRequest.Create
        var webRequest = WebRequest.Create("http://api.giphy.com/v1/gifs/search?q=" + "cute cat" + "&api_key=...") as HttpWebRequest;
        if (webRequest == null)
        {
            return;
        }

        webRequest.ContentType = "application/json";
        webRequest.UserAgent = "Nothing";

        using (var s = webRequest.GetResponse().GetResponseStream())
        {
            using (var sr = new StreamReader(s))
            {
                var Json = sr.ReadToEnd(); // json response from web api request
                dynamic data = JsonConvert.DeserializeObject(Json); // json to c# objects
                //(data.images).ForEach(Console.WriteLine);
                System.Console.WriteLine(data);

            }
        }

        Console.ReadLine();
    }
}

but when trying to access data[0] I get:

System.ArgumentException: 'Accessed JObject values with invalid key value: 0. Object property name expected.'

I also tried without dynamic with the help of json2csharp that did not work either.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Eva Cohen
  • 485
  • 1
  • 9
  • 24

3 Answers3

0

The very short answer is JArray.

I just checked and there even are examples of how to use it here on SO, for example at How to access elements of a JArray

However, since you didn't provide the data that is being de-serialized it's impossible to say if JArray is the answer for your problem.

tymtam
  • 31,798
  • 8
  • 86
  • 126
0

The response is an object that has a data property to an array. You cannot access properties of an object using integers, only strings.

You should pay attention to what the response actually looks like, don't guess.

You'll probably want to do something like this:

dynamic response = JsonConvert.DeserializeObject(Json);
foreach (var data in response.data)
{
    Console.WriteLine(data.images);
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
0

Try this..

var dataList=JsonConvert.DeserializeObject<List<ClassModel>>(data.ToString());

ClassModel should be a class equivalent to the object which is being sent as response from the api.

Sumit raj
  • 821
  • 1
  • 7
  • 14