生成JSON阵列WCF(Generate JSON array with WCF)

2019-06-25 08:16发布

我开发这个返回一个WCF Web服务:

{
    "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"
    }
]

Answer 1:

问题就在这里:

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


Answer 2:

这种行为也可以被设置为通过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>


文章来源: Generate JSON array with WCF
标签: c# json wcf rest