WCF服务返回简单的JSON结果

时间:2013-08-06 13:06:32

标签: c# json wcf service

我试图找出返回以下JSON字符串的最简单方法:

{"0":"bar1","1":"bar2","2":"bar3"}

我能够将类似下面的类对象返回给JSON:

Person person = new Person()
{
    foo1 = "bar1",
    foo2 = "bar2",
    foo3 = "bar3"
};

{"foo1":"bar1","foo2":"bar2","foo3":"bar3"}

我只是想知道如何将键作为整数字符串返回?

1 个答案:

答案 0 :(得分:1)

您可以使用[DataMember]属性(使用Name属性)更改序列化JSON中属性的名称,如下所示。

public class StackOverflow_18081074
{
    [DataContract]
    public class Person
    {
        [DataMember(Name = "0")]
        public string Foo1 { get; set; }
        [DataMember(Name = "1")]
        public string Foo2 { get; set; }
        [DataMember(Name = "2")]
        public string Foo3 { get; set; }
    }
    [ServiceContract]
    public class Service
    {
        [WebGet]
        public Person Get()
        {
            return new Person
            {
                Foo1 = "bar1",
                Foo2 = "bar2",
                Foo3 = "bar3"
            };
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/Get"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}