1

C# codes :

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BTC_Changex
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            double bitcoin_price_dollar = bitcoin_price_method();
        }

        public static double bitcoin_price_method()
        {
            double bitcoin_price = 8500;

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd");
                req.Method = "GET";
                req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8";
                req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
                req.ContentType = "text/html; charset=utf-8";
                req.Referer = "";
                req.KeepAlive = true;
                req.Timeout = 25000;
                req.AllowAutoRedirect = true;

                CookieContainer cookieJar1 = new CookieContainer();
                req.CookieContainer = cookieJar1;

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                foreach (Cookie cookie in res.Cookies)
                {
                    cookieJar1.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), "/", cookie.Domain));
                }

                Stream Stream = res.GetResponseStream();
                StreamReader reader = new StreamReader(Stream);
                string reader_str = reader.ReadToEnd();

                var obj = JObject.Parse(reader_str);
                string bitcoin_price_str = ((string)obj["0"]["current_price"]).Trim().Replace(",", "");
                bitcoin_price = double.Parse(bitcoin_price_str);

                reader.Close();
                Stream.Close();
                res.Close();
            }
            catch (Exception ex)
            {

            }

            return bitcoin_price;
        }
    }
}

I have error in this line : var obj = JObject.Parse(reader_str);

Error Message :

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.

What is the problem & how can i fix it?



Edit :
Here is reader_str : https://pastebin.com/fyv7GPVH

5
  • can you share some info about reader_str? Commented Apr 24, 2020 at 13:44
  • Here is reader_str : pastebin.com/fyv7GPVH Commented Apr 24, 2020 at 13:49
  • Also you can open that url in firefox - you will see there is no problem about that json. what is wrong? Commented Apr 24, 2020 at 13:50
  • The result its ok i thinkits cause of you are trying to parse array to object. Commented Apr 24, 2020 at 14:05
  • Just find the solution I mention both ways using jobjects or object. Hope it helps Commented Apr 24, 2020 at 14:26

1 Answer 1

2

The JSON you are receiving is an array of objects and you cant convert it to object.

 var objs = JArray.Parse(reader_str).ToObject<List<object>>();
 string bitcoin_price_str = ((string)((objs[0] as JObject)["current_price"])).Trim().Replace(",", "");

By default JArray containts list of key value pairs jobjects that you can assign them to c# objects. Also I suggest you to use JObject instead of objects and by converting to string we have access to string index not object.

var objs = JArray.Parse(reader_str).ToObject<List<JObject>>();
string bitcoin_price_str = objs[0]["current_price"].ToString().Trim().Replace(",", "");
//or
var objs = JArray.Parse(reader_str).ToObject<List<JObject>>();
string bitcoin_price_str2 = objs[0].GetValue("current_price").ToString().Trim().Replace(",", "");
Sign up to request clarification or add additional context in comments.

3 Comments

Hi , i was having same problem as described in question ( json string having arrays) and your answer helped -> i have a list of JObject and iterated over each object in list . But if a key has its value as object as i want to access value of that nested key , how to do that ? would be grateful to any insight
@Chahat Can you send your JSON and what property you want?
I found the solution just now.For a nested key like { "abc" : { "name" : "Chahat" }) -> to extract "name value" , I just did used obj["abc.name"] . Thankyou though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.