4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でREST APIにアクセスする(JSONでparameterをやりとりしたい)

Last updated at Posted at 2019-05-10

内容

rest if 通信、rest if アクセス
たまにしかC#を使わないので自分のためのメモ

C#でrest fullなAPIにアクセスしようとするとなかなかめんどくさい。

phpやpythonでjsonを使うことに慣れていると、いちいちクラス作ったりとてもめんどくさい。
理想はクラスを経由してaccessするのがいいんだけど・・やっぱりめんどくさい。
クラスを前提に作らなきゃいけないC#ではphp,pythonで作られたサービスの癖についていくのがキツイです。
キーの存在確認とかできないとか。。C#のがお行儀のよいJSONばかりでね。:joy:

環境

パッケージマネージャで以下を実行

Install-Package DynamicJson -Version 1.2.0
Install-Package Newtonsoft.Json -Version 12.0.2
Install-Package RestSharp

コード

Elasticsearchにアクセスするコード
指定時刻を超えるdocumentを持ってくるサンプル

using Newtonsoft.Json;
using RestSharp;
using Codeplex.Data;


/////////////////////////

RestClient client = new RestClient("http://ここにURL.co.jp");
//client.Authenticator = new HttpBasicAuthenticator("username", "password"); 認証が必要な場合

RestRequest request = new RestRequest("/ここにresourceのURL/",Method.POST);

//リクエストJSONは無名で作った方が楽
object x = new { query = new { range = new {
                   occurred_at = new { 
                     gt = "2017-08-16 16:18:00+0900", lte = "now", 
                     format = "yyyy-MM-dd HH:mm:ssZ" } } } };

request.AddJsonBody(x);
request.RequestFormat = DataFormat.Json;

var response = client.Execute(request);

//ここにドキュメントを処理するコード
var jsonObj = DynamicJson.Parse(response.Content);
var total=jsonObj.hits.total;

foreach (var hit in jsonObj.hits.hits)
{

    var at=hit._source.occurred_at;

}


文字列でアクセスする
添え字でよかったんか・・

dynamic djson=DynamicJson.Parse(cjson)
string name=djson["name"]

キー存在の確認


        private bool contains(dynamic value, string index)
        {
            foreach (string key in value.GetDynamicMemberNames())
            {
                if (index.Equals(key))
                {
                    return true;
                }
            }
            return false;
        }

キー存在の確認がIEnumerableではできないからGetDynamicMemberNames()で反復して検索するしかなった。
もっといい方法があればだれか教えてください。
(ICollectionに食わせればいいんだろうなぁ~)
追記:IsDefinedが使えることが分かった

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?