2012-04-09 57 views
2

我開發返回此一個WCF Web服務:生成JSON陣列WCF

{ 
    "allFormsResult": [ 
     { 
      "FormId": 1, 
      "FormName": "Formulario 1" 
     }, 
     { 
      "FormId": 2, 
      "FormName": "Formulario 2" 
     }, 
     { 
      "FormId": 3, 
      "FormName": "Formulario 3" 
     } 
    ] 
} 

這是代碼:

public class RestServiceImpl : IRestServiceImpl 
    { 
     public List<FormContract> allForms() 
     { 
      List<FormContract> list = null; 
      using (var vAdmEntities = new ADMDatabase.ADMEntities()) 
      { 
       list = new List<FormContract>(); 
       foreach (var form in vAdmEntities.Form) 
       { 
        FormContract formC = new FormContract 
        { 
         FormName = form.name.Trim(), 
         FormId = form.formId 
        }; 
        list.Add(formC); 
       } 
      } 

      return list; 
     } 
    } 

我該怎麼做才能生成它以這種方式?

[ 
    { 
     "FormId": 1, 
     "FormName": "Formulario 1" 
    }, 
    { 
     "FormId": 2, 
     "FormName": "Formulario 2" 
    }, 
    { 
     "FormId": 3, 
     "FormName": "Formulario 3" 
    } 
] 
+0

不確定,但嘗試返回'FormContract []'而不是'List '。 – 2012-04-09 13:30:18

+0

不,它不起作用。 – VansFannel 2012-04-09 13:34:28

回答

4

的問題是在這裏:

namespace ADM 
{ 
    [ServiceContract] 
    public interface IRestServiceImpl 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", 
      ResponseFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.Wrapped, 
      UriTemplate = "forms/")] 
     List<FormContract> allForms(); 
    } 
} 

我必須用這種方式:

namespace ADM 
{ 
    [ServiceContract] 
    public interface IRestServiceImpl 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", 
      ResponseFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.Bare, 
      UriTemplate = "forms/")] 
     List<FormContract> allForms(); 
    } 
} 

更改BodyStyle

BodyStyle = WebMessageBodyStyle.Bare 
0

這種行爲也可以SE t作爲默認通過Web.Config,而不需要將屬性直接添加到合同中。

<services> 
    <service name="MyServiceNameSpace.MyServiceClass"> 
    <endpoint 
     address="http://yourservicedomain.ext/MyServiceClass.svc/" 
     binding="webHttpBinding" 
     contract="MyServiceNameSpace.MyServiceContract" 
     behaviorConfiguration="MyEndpointBehavoir" 
     listenUri="/" />   
    </service>  
</services> 

<behaviors> 
    <endpointBehaviors> 
    <behavior name="MyEndpointBehavoir"> 
     <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Bare"/> 
    </behavior>   
    </endpointBehaviors> 
</behaviors>