2012-04-09 62 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>