.NET/Web APIからJSONを取得し値を表示する・DataContractJsonSerializer
の編集
Top
/
.NET
/
Web APIからJSONを取得し値を表示する・DataContractJsonSerializer
[
トップ
] [
編集
|
差分
|
バックアップ
|
添付
|
リロード
] [
新規
|
一覧
|
検索
|
最終更新
|
ヘルプ
]
-- 雛形とするページ --
.NET
.NET/.NETでpingを実現する・System.Net.NetworkInformation.Ping
.NET/ARPテーブルを取得し表示するサンプル・GetIpNetTable
.NET/CPUコア毎の使用率を取得する
.NET/CPU使用率を取得する
.NET/DateとDateTimeの違い
.NET/HttpClientを使って指定したURLのページを取得する
.NET/IPv4からMACアドレス取得する・SendARP
.NET/IPアドレスからホスト名を取得するサンプルコード
.NET/ListのStringをカンマ区切りにする方法
.NET/Listを配列に配列をListに変換する
.NET/NET6.0でSQLiteを使ってみた Microsoft.Data.Sqlite
.NET/ODBCを使用してデータベースに接続しSQLを実行するサンプル
.NET/String.Splitで空要素を残す、空要素を削除するオプションについて
.NET/StringBuilderをバイト配列に変換する
.NET/Stringの配列をCSVにする方法
.NET/UNIX時間への変換・DateTimeOffset
.NET/UNIX時間をDateTimeOffset, DateTimeにする
.NET/Web APIからJSONを取得し値を表示する・DataContractJsonSerializer
.NET/WMIを使って物理メモリ・仮想メモリの使用量等を取得する
.NET/アルファベットを大文字、小文字に変換する
.NET/インストールされているODBCドライバ一覧を取得するサンプル
.NET/コンソールプログラムからトースト通知をするサンプル
.NET/サスペンド前・復帰の時に処理を行いたい
.NET/スペースのみの文字列、空の文字列、サイズ0の文字列を判定する
.NET/スリープの抑止、モニター電源オフの抑止のサンプルコード
.NET/ターゲットにしている.NETを確認する操作手順
.NET/テキストファイルの読込・ReadAllText,ReadAllLines
.NET/テキストファイルの読込・StreamReader
.NET/テンポラリファイルの作成・ランダムな文字列の作成を作成する
.NET/テンポラリファイル名を取得する・GetRandomFileName
.NET/ディレクトリの有無を確認する
.NET/ネットワークカードの各種情報を取得するサンプルコード
.NET/バイト配列にファイルの内容をすべて読み込む
.NET/バイナリーファイルの作成・リード・ライト
.NET/ファイルなの?ディレクトリなの?の判別
.NET/ファイルの有無を確認する
.NET/ファイル一覧を取得する・GetFiles,EnumerateFiles
.NET/プログラムに渡された引数を取得する方法
.NET/ユーザーが無操作の状態を取得する・GetLastInputInfo
.NET/三項演算子のサンプルコード
.NET/四捨五入をするときはMidpointRounding.AwayFromZeroにすること
.NET/指定した時間間隔でイベントを発行する・Timer
.NET/数値を指定した桁数分ゼロで埋めたい・ToString
.NET/文字列(String)を左右逆転し文字列(String)で返却する方法
.NET/文字列をバイト配列に変換・バイト配列を文字列に変換
.NET/文字列を区切り文字で分割する方法・Split
.NET/文字列宣言の先頭の@について
.NET/文字列数値を指定した桁数分ゼロで埋めたい・PadLeft
.NET/文字列日付をDateTimeに変換する
.NET/文字列配列orList配列に指定した文字列が存在するかを確認する方法
.NET/時間(日数+時間)が格納できるTimeSpan
.NET/月末の日を取得する方法・DaysInMonth
.NET/現在の日時を取得する
.NET/符号付バイトsbyte,符号なしbyteをintegerに変換する
.NET/管理者として実行されているかどうか確認するサンプルコード
.NET/連想配列(ハッシュ)のキーと値を取得する
.NET/連想配列(ハッシュ)を使ってみる・Dictionary
.NET/閏年かを調べる方法
AutoTicketLinkName
FrontPage
MenuBar
OSS
OSS/XYM日本円価格(シンボル日本円価格 (XYMJPYPrice)
OSS/ビットコイン日本円価格(ビットコイン日本円価格 (BitcoinJPYPrice)
RecentDeleted
VS
VS/Debug.Writeをイミディエイトウィンドウに出力する方法
VS/Visual Studio 2022に Spy++をインストールする手順
VS/VS2022の配色テーマの変更操作
VS/XAML編集に使うツールボックスの再表示する操作手順
VS/インデントなどコードを整形するショートカットの紹介
VS/コメントにするショートカットキー
VS/ショートカットキーで大文字・小文字に変換する
VS/ビルド中に中断したい場合の操作手順
WPF
WPF/DataGridを使ってみる
WPF/起動してもMainWindowを表示したくない場合
お約束
プライバシーポリシー
最初にお読みください
#navi(../) * Web APIからJSONを取得し値を表示する・DataContractJsonSerializer [#p08ec626] .NET標準の''DataContractJsonSerializer''を使用して、bitflyer仮想通貨取引所が公開している Ticker Web APIにアクセスし、~ 取得したJSONをデシリアライズし画面に表示するまでのサンプルコードになります。~ ''本サンプルコードでアクセスするbitflyerのTicker Web API'' -[[https://lightning.bitflyer.com/docs?lang=ja#ticker]] サンプルコードは C#, Visual Basic(VB)を公開しています。~ 尚、HTTPによるアクセスは、以下リンクの記事のサンプルコードを流用しました。 -[[HttpClientを使って指定したURLのページを取得する>.NET/HttpClientを使って指定したURLのページを取得する]]~ #htmlinsert(windev-top.html) #contents * 関連サイト [#oe3a9a14] -[[Microsoft .NET DataContractJsonSerializer クラス>https://docs.microsoft.com/ja-jp/dotnet/api/system.runtime.serialization.json.datacontractjsonserializer]] * 関連記事 [#m923e443] -[[HttpClientを使って指定したURLのページを取得する>.NET/HttpClientを使って指定したURLのページを取得する]] * 動作環境 [#y668fb01] -Windows 10 ver.1909 -Visual Studio 2019 -.NET Core 3.1 -コンソールアプリケーション * サンプルコード [#m4e2257d] 以下にC#,Visual Basic(VB)のサンプルコードを紹介します。~ また、実行時のキャプチャもあります。 ** C# [#d7559a6c] 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 [#b2173783] 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 ** 実行結果 [#i069c584] 上記サンプルコードの実行結果になります。 #ref(01.png) 以上、.NET標準の DataContractJsonSerializer を使ってJSONをデシリアライズし出力するサンプルコードの紹介でした。 #htmlinsert(windev-btm.html)
タイムスタンプを変更しない
#navi(../) * Web APIからJSONを取得し値を表示する・DataContractJsonSerializer [#p08ec626] .NET標準の''DataContractJsonSerializer''を使用して、bitflyer仮想通貨取引所が公開している Ticker Web APIにアクセスし、~ 取得したJSONをデシリアライズし画面に表示するまでのサンプルコードになります。~ ''本サンプルコードでアクセスするbitflyerのTicker Web API'' -[[https://lightning.bitflyer.com/docs?lang=ja#ticker]] サンプルコードは C#, Visual Basic(VB)を公開しています。~ 尚、HTTPによるアクセスは、以下リンクの記事のサンプルコードを流用しました。 -[[HttpClientを使って指定したURLのページを取得する>.NET/HttpClientを使って指定したURLのページを取得する]]~ #htmlinsert(windev-top.html) #contents * 関連サイト [#oe3a9a14] -[[Microsoft .NET DataContractJsonSerializer クラス>https://docs.microsoft.com/ja-jp/dotnet/api/system.runtime.serialization.json.datacontractjsonserializer]] * 関連記事 [#m923e443] -[[HttpClientを使って指定したURLのページを取得する>.NET/HttpClientを使って指定したURLのページを取得する]] * 動作環境 [#y668fb01] -Windows 10 ver.1909 -Visual Studio 2019 -.NET Core 3.1 -コンソールアプリケーション * サンプルコード [#m4e2257d] 以下にC#,Visual Basic(VB)のサンプルコードを紹介します。~ また、実行時のキャプチャもあります。 ** C# [#d7559a6c] 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 [#b2173783] 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 ** 実行結果 [#i069c584] 上記サンプルコードの実行結果になります。 #ref(01.png) 以上、.NET標準の DataContractJsonSerializer を使ってJSONをデシリアライズし出力するサンプルコードの紹介でした。 #htmlinsert(windev-btm.html)
テキスト整形のルールを表示する
添付ファイル:
01.png
277件
[
詳細
]