Open棟梁Project - マイクロソフト系技術情報 Wiki
WCFやWebAPIで、指定のREST Formatに適合するJSONを返す方法を説明する。
まず、どのようなJSONを出力したいのかを確認します。
これがなければ、始まりません。
次に、出力したいJSONに合わせて、クラスやプロパティを定義します。
基本的には、以下のルールに従って、クラスやプロパティを定義します。
出力したいJSON | 定義するクラス・プロパティ |
{ "key1" : "value1", "key2" : "value2" } | public class Sample { string key1 { get; set; } string key2 { get; set; } } |
[ "1", "2", "3" ] | List<string> listData { get; set; } |
{ "key1" : [ "1", "2", "3" ] } | public class Sample { List<string> key1 { get; set; } } |
{ "key" : { "key1" : "value1", "key2" : "value2" } } | public class Sample { string key1 { get; set; } string key2 { get; set; } } public class Sample2 { Sample key { get; set; } } |
[ { "key1" : "value1", "key2" : "value2" }, { "key1" : "value3", "key2" : "value4" } ] | public class Sample { string key1 { get; set; } string key2 { get; set; } } List<Sample> listData { get; set; } |
BeanとDictionaryでSerializeされるJSONのformatが異なる。
{ "Prop1": "Value1", "Prop2": "Value2" }
[ { "Key": "Prop1", "Value": "Value1" }, { "Key": "Prop2", "Value": "Value2" } ]
WCFでJSONを返す場合、既定ではDataContractJsonSerializer?が使用されます。
[ServiceContract] public interface IJSONService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetJson")] Sample GetJson(); } public class JSONService : IJSONService { public Sample GetJson() { // JSON にシリアライズする元となるオブジェクトを作成する Sample sample = new Sample() { StringKey = "StringValue", IntKey = 123, ListKey = new List<string>() { "List1", "List2", "List3" } }; // クライアントにデータを返す return sample; } } public class Sample { public string StringKey { get; set; } public int IntKey { get; set; } public List<string> ListKey { get; set; } }
<system.serviceModel> <services> <service name="WebApplication1.JSONService"> <endpoint address="" binding="webHttpBinding" behaviorConfiguration="MyBehavior" contract="WebApplication1.IJSONService" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="MyBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel>
{"IntKey":123,"ListKey":["List1","List2","List3"],"StringKey":"StringValue"}
[ServiceContract] public interface IJSONService2 { [OperationContract] [WebGet(UriTemplate = "GetJson")] Message GetJson(); } public class JSONService2 : IJSONService2 { public Message GetJson() { // JSON にシリアライズする元となるオブジェクトを作成する Sample2 sample = new Sample2() { key = new Dictionary<string, string>() { {"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"} } }; // JSON.NET を使用して JSON 形式にシリアライズ string jsonStr = JsonConvert.SerializeObject(sample); // 'X-Content-Type-Options: nosniff' ヘッダーを追加する WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Content-Type-Options", "nosniff"); // JSON を返す return WebOperationContext.Current.CreateTextResponse(jsonStr, "application/json; charset=utf-8", Encoding.UTF8); } } public class Sample2 { public Dictionary<string, string> key { get; set; } }
<system.serviceModel> <services> <service name="WebApplication1.JSONService2"> <endpoint address="" binding="webHttpBinding" behaviorConfiguration="MyBehavior" contract="WebApplication1.IJSONService2" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="MyBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel>
{"key":{"key1":"value1","key2":"value2","key3":"value3"}}
ASP.NET Web APIでは、既定でJSON.NETによってSerializeされます。
このため、Dictionary型も問題なくSerializeできます。
public class ValuesController : ApiController { // GET api/values public Sample Get() { // JSON にシリアライズする元となるオブジェクトを作成する Sample sample = new Sample() { key = new Dictionary<string, string>() { {"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"} } }; // JSON を返す return sample; } } public class Sample { public Dictionary<string, string> key { get; set; } }
{"key":{"key1":"value1","key2":"value2","key3":"value3"}}
はやり、Serializer毎に挙動が違うので、
RESTのAPIのデータ・コントラクトは、XMLやJSONのformatレベルで行うのが良いようです。
以下を参考に、Tomcat 上で実行する Java の Web API を作成してみました。
{ "Prop1": "Value1", "Prop2": "Value2" }
→ .NET と「同じ」挙動
{ "Prop1": "Value1", "Prop2": "Value2" }
→ .NET と「異なる」挙動
数個、AzureのREST APIをピックアップしてみました。
GrsourceGroup?のnameが RESTのUriに含まれていて、ResponceがJOSN形式で返されます
ResponceがHTTP 200 だけのもあります
呼び出すパラメタが大きく、変更を加える操作は、PUT で行われ、Request Body に パラメタがJOSN形式で渡されます。
やはり、JSONのformatが明記されており、formatレベルでデータ・コントラクトを結ぶ必要があります。