C#解析JSON API数组 [英] C# parse JSON API array
问题描述
我正在尝试从C#中的此api获取最后一个"对象: https://bittrex.com/api/v1.1/public/getmarketsummary?market=usdt-btc
I'm trying to get the "Last" Object from this api in C#: https://bittrex.com/api/v1.1/public/getmarketsummary?market=usdt-btc
我已经有了将数组放入C#代码中的脚本,但是我不知道如何获取此对象,我在Google周围四处寻求帮助,并且发现了以下内容:
I already have the script to get the array into my C# code but i don't know how to get this Object, i have googled around for help and i found things like these: https://www.codementor.io/andrewbuchan/how-to-parse-json-into-a-c-object-4ui1o0bx8 but it did not work for me.
编辑 工作版本在这里: http://dotnetfiddle.net/5VFof9
EDIT The working version is here: http://dotnetfiddle.net/5VFof9
//GET api array
string GET(string url) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
decimal coin_price() {
String array = GET("https://bittrex.com/api/v1.1/public/getmarketsummary?market=usdt-btc");
decimal price = 0;
//return price in price var
return price;
}
private void Form1_Load(object sender, EventArgs e) {
price.Text = ""; //Display price here
}
推荐答案
您可以使用JSON.NET:
You can use JSON.NET:
public static void Main()
{
var url = "https://bittrex.com/api/v1.1/public/getmarketsummary?market=usdt-btc";
// for a simple get, use WebClient
var json = new WebClient().DownloadString(url);
// learn more on https://www.newtonsoft.com/json
var root = JsonConvert.DeserializeObject<RootObject>(json);
// root.Results.Last() is your last item
// learn more on Last() at https://msdn.microsoft.com/fr-fr/library/bb358775(v=vs.110).aspx
Console.WriteLine(root.Result.Last().TimeStamp);
}
// generated with http://json2csharp.com/ (VS has a builtin with edit>past special)
public class Result
{
public string MarketName { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Volume { get; set; }
public double Last { get; set; }
public double BaseVolume { get; set; }
public DateTime TimeStamp { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
public int OpenBuyOrders { get; set; }
public int OpenSellOrders { get; set; }
public double PrevDay { get; set; }
public DateTime Created { get; set; }
}
public class RootObject
{
public bool Success { get; set; }
public string Message { get; set; }
public List<Result> Result { get; set; }
}
这篇关于C#解析JSON API数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!