はじめに
先日の REST のサンプルを JSON に対応させます。
JSON 対応は簡単
サービスコントラクトを修正。WebGet 属性に注目!
[ServiceContract] public interface IProductService { [OperationContract] [WebGet(UriTemplate = "/product/{id}/", ResponseFormat = WebMessageFormat.Json)] // ←これを追加 Product GetProduct(string id); }
ResponseFormat プロパティに Json を指定しています。これだけ。
レスポンスが JSON になっているか確認
確認用のクライアントを作成します
class Program { static void Main(string[] args) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( "http://localhost:8000/ProductService/product/2/"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 本文を取り出す Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string result = reader.ReadToEnd(); Console.WriteLine(result); Console.ReadLine(); response.Close(); } }
クライアントの実行結果
{"Id":"2","Name":"ファンタ","Price":"120"}