您好我试图从文本文件中读取json数据,但它不起作用。 当我尝试从网站获取数据然后它工作正常。 有人知道解决这个问题的解决方案吗? 提前谢谢。
private void Form1_Load(object sender, EventArgs e)
{
string path = @"C:\Users\spacefrog\Documents\Visual Studio 2017\Projects\json_test_solution\json_test\bin\Debug\test.json";
// Stream stream = File.OpenRead(path);
WebClient client = new WebClient();
Stream stream = client.OpenRead("https://www.cryptocompare.com/api/data/coinlist/"); // works perfect
/*
Stream stream = client.OpenRead(path); // doesn't work
Stream stream = File.OpenRead(path); // doesn't work
*/
/* File Data content (same as website)
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
*/
StreamReader reader = new StreamReader(stream);
JObject json = JObject.Parse(reader.ReadLine());
stream.Close();
MessageBox.Show((string)json["Response"]);
}
答案 0 :(得分:1)
JObject json = JObject.Parse(reader.ReadLine());
JSON.NET Parser如何解析第一行?看看你的评论,第一行似乎是
{
看起来不像是有效的JSON对象。看看ReadToEnd方法。 顺便说一句,您可能希望在使用范围内使用StreamReader。
答案 1 :(得分:0)
您不必使用临时文件来解析该json
comm.Parameters.Add(new SqlParameter("@getReceipt", receiptbox.Text));
如果你真的想保存到文件,你可以使用
WebClient webClient = new WebClient();
var json = webClient.DownloadString("https://www.cryptocompare.com/api/data/coinlist/");
var rootObj = JsonConvert.DeserializeObject<SOTest.RootObject>(json);
//OR var jObj = JObject.Parse(json);
或将上面的json写入文件
webClient.DownloadFile(url,filename);
或者如果您想要 client.OpenRead 方式
File.WriteAllText(filename, json);
var f = File.Create(filename);
stream.CopyTo(f);