Web APIからJSONを取得し値を表示する・DataContractJsonSerializer †.NET標準のDataContractJsonSerializerを使用して、bitflyer仮想通貨取引所が公開している Ticker Web APIにアクセスし、 サンプルコードは C#, Visual Basic(VB)を公開しています。 関連サイト †関連記事 †動作環境 †
サンプルコード †以下にC#,Visual Basic(VB)のサンプルコードを紹介します。 C# †using System; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization.Json; class Program { static void Main(string[] args) { string endpoint = @"https://api.bitflyer.com/v1/"; string tickerApi = @"ticker?product_code="; string product_code = @"BTC_JPY"; Program app = new Program(); HttpClient client = new HttpClient(); string responseJson = (app.HttpContent(endpoint + tickerApi + product_code , client)).Result; Console.WriteLine("== TICKER BTC_JPY TICKER ==\n{0}",responseJson); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.FFF") }; Ticker deserialized; DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Ticker), settings); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseJson), false)) { deserialized = js.ReadObject(ms) as Ticker; } Console.WriteLine("== DESERIALIZED TICKER =="); app.ShowTicker(deserialized); } [System.Runtime.Serialization.DataContract] public class Ticker { [System.Runtime.Serialization.DataMember(Name = "product_code")] public string product_code { get; set; } [System.Runtime.Serialization.DataMember(Name = "timestamp")] public DateTime timestamp { get; set; } [System.Runtime.Serialization.DataMember(Name = "tick_id")] public int tick_id { get; set; } [System.Runtime.Serialization.DataMember(Name = "best_bid")] public Decimal best_bid { get; set; } [System.Runtime.Serialization.DataMember(Name = "best_ask")] public Decimal best_ask { get; set; } [System.Runtime.Serialization.DataMember(Name = "best_bid_size")] public Decimal best_bid_size { get; set; } [System.Runtime.Serialization.DataMember(Name = "total_bid_depth")] public Decimal total_bid_depth { get; set; } [System.Runtime.Serialization.DataMember(Name = "total_ask_depth")] public Decimal total_ask_depth { get; set; } [System.Runtime.Serialization.DataMember(Name = "ltp")] public Decimal ltp { get; set; } [System.Runtime.Serialization.DataMember(Name = "volume")] public Decimal volume { get; set; } [System.Runtime.Serialization.DataMember(Name = "volume_by_product")] public Decimal volume_by_product { get; set; } } private void ShowTicker(Ticker t) { Console.WriteLine("product_code :{0}", t.product_code); Console.WriteLine("timestamp :{0}", t.timestamp); Console.WriteLine("tick_id :{0}", t.tick_id); Console.WriteLine("best_bid :{0}", t.best_bid); Console.WriteLine("best_ask :{0}", t.best_ask); Console.WriteLine("best_bid_size :{0}", t.best_bid_size); Console.WriteLine("total_bid_depth :{0}", t.total_bid_depth); Console.WriteLine("total_ask_depth :{0}", t.total_ask_depth); Console.WriteLine("ltp :{0}", t.ltp); Console.WriteLine("volume :{0}", t.volume); Console.WriteLine("volume_by_product:{0}", t.volume_by_product); } private async Task<string> HttpContent(string url, HttpClient clinet) { HttpResponseMessage response = null; try { response = await clinet.GetAsync(url); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return await response.Content.ReadAsStringAsync(); } catch (Exception ex) { Console.WriteLine("Exception Message :{0} ", ex.Message); } return null; } } Visual Basic †Imports System.IO Imports System.Text Imports System.Net.Http Imports System.Runtime.Serialization.Json Module Program Sub Main(args As String()) Dim endpoint As String = "https://api.bitflyer.com/v1/" Dim tickerApi As String = "ticker?product_code=" Dim product_code As String = "BTC_JPY" Dim client As HttpClient = New HttpClient() Dim responseJson As String = (HttpContent(endpoint & tickerApi & product_code, client)).Result Console.WriteLine("== TICKER BTC_JPY TICKER ==" & vbCrLf & "{0}", responseJson) Dim settings As DataContractJsonSerializerSettings = New DataContractJsonSerializerSettings With { .DateTimeFormat = New System.Runtime.Serialization.DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.FFF") } Dim deserialized As Ticker Dim js As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(Ticker), settings) Using ms = New MemoryStream(Encoding.UTF8.GetBytes(responseJson), False) deserialized = TryCast(js.ReadObject(ms), Ticker) End Using Console.WriteLine("== DESERIALIZED TICKER ==") ShowTicker(deserialized) End Sub <System.Runtime.Serialization.DataContract> Public Class Ticker <System.Runtime.Serialization.DataMember(Name:="product_code")> Public Property product_code As String <System.Runtime.Serialization.DataMember(Name:="timestamp")> Public Property timestamp As DateTime <System.Runtime.Serialization.DataMember(Name:="tick_id")> Public Property tick_id As Integer <System.Runtime.Serialization.DataMember(Name:="best_bid")> Public Property best_bid As Decimal <System.Runtime.Serialization.DataMember(Name:="best_ask")> Public Property best_ask As Decimal <System.Runtime.Serialization.DataMember(Name:="best_bid_size")> Public Property best_bid_size As Decimal <System.Runtime.Serialization.DataMember(Name:="total_bid_depth")> Public Property total_bid_depth As Decimal <System.Runtime.Serialization.DataMember(Name:="total_ask_depth")> Public Property total_ask_depth As Decimal <System.Runtime.Serialization.DataMember(Name:="ltp")> Public Property ltp As Decimal <System.Runtime.Serialization.DataMember(Name:="volume")> Public Property volume As Decimal <System.Runtime.Serialization.DataMember(Name:="volume_by_product")> Public Property volume_by_product As Decimal End Class Private Sub ShowTicker(ByVal t As Ticker) Console.WriteLine("product_code :{0}", t.product_code) Console.WriteLine("timestamp :{0}", t.timestamp) Console.WriteLine("tick_id :{0}", t.tick_id) Console.WriteLine("best_bid :{0}", t.best_bid) Console.WriteLine("best_ask :{0}", t.best_ask) Console.WriteLine("best_bid_size :{0}", t.best_bid_size) Console.WriteLine("total_bid_depth :{0}", t.total_bid_depth) Console.WriteLine("total_ask_depth :{0}", t.total_ask_depth) Console.WriteLine("ltp :{0}", t.ltp) Console.WriteLine("volume :{0}", t.volume) Console.WriteLine("volume_by_product:{0}", t.volume_by_product) End Sub Private Async Function HttpContent(ByVal url As String, ByVal clinet As HttpClient) As Task(Of String) Dim response As HttpResponseMessage = Nothing Try response = Await clinet.GetAsync(url) response.EnsureSuccessStatusCode() Dim responseBody As String = Await response.Content.ReadAsStringAsync() Return Await response.Content.ReadAsStringAsync() Catch ex As Exception Console.WriteLine("Exception Message :{0} ", ex.Message) End Try Return Nothing End Function End Module 実行結果 †上記サンプルコードの実行結果になります。 以上、.NET標準の DataContractJsonSerializer を使ってJSONをデシリアライズし出力するサンプルコードの紹介でした。 |