3
1

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 5 years have passed since last update.

【C#】DynamicJsonを使った JSON API リクエスト

Last updated at Posted at 2019-04-11

#DynamicJsonを使った JSON API リクエスト

VisualStudio2010 (古い…)C# アプリで JSON API を叩きたい!
ディクショナリ(ハッシュ)パラメータのみ対応、
複雑な構成はここでは考えません・・・

環境

開発PC: Windows 10
VisualStudio: 2010
DynamiCJson: 1.2.0
C#

VS2010 プロジェクトにインストール

プロジェクトのパッケージマネージャコンソールを開いてコマンド実行

パッケージマネージャコンソール
Install-Package DynamicJson -Version 1.2.0

使い方説明など

関数用意

SampleJson.cs
        /// <summary>
        /// ディクショナリからJSON文字列生成
        /// </summary>
        /// <param name="dict">パラメータディクショナリ</param>
        /// <returns>JSON文字列</returns>
        public static string DictionaryToJson(IDictionary<string, string> dict)
        {
            // パラメータディクショナリから json 文字列生成
            var entries = dict.Select(d =>
                string.Format("\"{0}\": \"{1}\"", d.Key, string.Join(",", d.Value)));
            return "{\n" + string.Join(",\n", entries) + "\n}";
        }

API呼び出し用メソッド

  1. JsonWebApi
SampleJson.cs
        /// <summary>
        /// JSONリクエストAPI
        /// </summary>
        /// <param name="url">あて先URL</param>
        /// <param name="spDic">パラメータディクショナリ</param>
        /// <param name="reqParam">リクエストパラメータ</param>
        /// <param name="resParam">レスポンスパラメータ</param>
        /// <returns>結果DynamicJson</returns>
        public static dynamic JsonWebApi(string url, IDictionary<string, string> spDic, ref string reqParam, ref string resParam) {

            // WebRequest 生成
            var req = WebRequest.Create(url);
            //Console.WriteLine("Uri:" + req.RequestUri.AbsoluteUri);

            var spJson = "";
            byte[] spData = { };
            reqParam = "";
            resParam = "";

            // リクエスト用 json 文字列生成
            spJson = DictionaryToJson(spDic);
            Console.WriteLine("JsonWebApi JSON:" + spJson);
            reqParam = spJson;

            spData = Encoding.UTF8.GetBytes(spJson);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.ContentLength = spData.Length;

            dynamic jsonResp = new DynamicJson();
            jsonResp.Result = "";
            jsonResp.Status = "";
            jsonResp.Code = "";
            jsonResp.Desc = "";

            try {
                using (Stream reqStream = req.GetRequestStream())
                    reqStream.Write(spData, 0, spData.Length);

                using (var res = req.GetResponse())
                using (var s = res.GetResponseStream()) {

                    // 結果読み取り
                    string respString = "";
                    using (var reader = new StreamReader(s, Encoding.UTF8))
                        respString = reader.ReadToEnd();
                    Console.WriteLine("JsonWebApi response:" + respString);
                    resParam = respString;

                    // json パース
                    var j = DynamicJson.Parse(respString);
                    if (j.IsDefined("Result")) {
                        jsonResp = j;
                    }
                    if (j.IsDefined("Status")) {
                        jsonResp.Status = j.Status;
                    }
                    jsonResp.Code = "200";
                    jsonResp.Desc = respString;
                }
            }
            // エラーハンドリング
            catch (WebException webex) {
                switch (webex.Status) {
                    case WebExceptionStatus.Timeout:
                    case WebExceptionStatus.NameResolutionFailure:
                    default:
                        Console.WriteLine("WebException has been occurred:" + webex.Message + ":" + reqParam + ":" + resParam);
                        break;
                }
                var exres = (HttpWebResponse)webex.Response;
                int statusCode = 0;
                if (exres != null) {
                    var status = exres.StatusCode;
                    statusCode = (int)status;
                    Console.WriteLine("StatusCode Error:" + statusCode.ToString() + ":" + reqParam + ":" + resParam);
                }
                jsonResp.Result = "WEB_EXCEPTION";
                jsonResp.Status = "WEB_EXCEPTION";
                jsonResp.Code = statusCode.ToString();
                jsonResp.Desc = webex.Message;
                if (req != null) req.Abort();
                if (exres != null) exres.Close();
            }
            finally {
                if (req != null) req.Abort();
            }
            return jsonResp;
        }

実行してみる

Program.cs
    static void Main(string[] args) {

            string reqParam = "";
            string resParam = "";
            string url = "https://jsonplaceholder.typicode.com/posts";
            SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
            dic.Add("Result", "SUCCESS");
            dic.Add("Status", "OK");

            var response = JsonWebApi(url, dic, ref reqParam, ref resParam);
            Console.WriteLine(response);
    }

以上、お疲れ様でした!

3
1
1

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?