从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象:StartArray。路径 , 第 1 行, 位置 1



C#代码:

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;
}
}
}

我在这行有错误:var obj = JObject.Parse(reader_str);

错误消息:

从JsonReader读取JObject时出错。当前JsonReader项不是一个对象:StartArray。路径",第1行,位置1。

问题出在哪里&我该怎么修



编辑:
这里是reader_str:https://pastebin.com/fyv7GPVH

您正在接收的JSON是一个对象数组,您无法将其转换为对象。

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

默认情况下,JArray包含键值对作业对象的列表,您可以将它们分配给c#对象。此外,我建议您使用JObject而不是对象,通过转换为字符串,我们可以访问字符串索引而不是对象。

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(",", "");

相关内容

  • 没有找到相关文章

最新更新