使用WCF生成JSON数组 [英] Generate JSON array with WCF

查看:68
本文介绍了使用WCF生成JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发返回以下内容的WCF Web服务:

I'm developing a WCF web service that returns this:

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

推荐答案

问题在这里:

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

我必须以这种方式使用它:

I have to use it this way:

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

这篇关于使用WCF生成JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆