20
32

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#でWebAPI叩いてJson形式の結果を受け取る処理メモ

Posted at

※C#初心者なのでメモです

環境

  • .NET Framework 3.5

4.0 からはDynamicJSONが使えるらしい

using追加

using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization

データコントラクト定義

[DataContract]
public class RequestResult
{
    [DataMember]
    public string data1 { get; set; }
    [DataMember]
    public string data2 { get; set; }
    [DataMember]
    public string data3 { get; set; }
    [DataMember]
    public string data4 { get; set; }
}

実処理

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://example.com/api/hoge");
    req.ContentType = "application/json";
    req.Method = "POST";

    using (var streamWriter = new StreamWriter(req.GetRequestStream()))
    {
        string jsonPayload = new JavaScriptSerializer().Serialize(new
        {
            hoge = "APIを",
            piyo = "叩く際に渡す",
            foo = "パラメータ"
        });
        streamWriter.Write(jsonPayload);
    }

    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    RequestResult result;
    using (res)
    {
        using (var resStream = res.GetResponseStream())
        {
            var serializer = new DataContractJsonSerializer(typeof(RequestResult));
            result = (RequestResult)serializer.ReadObject(resStream);
        }
    }

参考

20
32
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
20
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?