0

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

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

我完全有能力将以下类对象返回给 JSON:

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

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

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

4

1 回答 1

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();
    }
}
于 2013-08-06T22:45:24.307 回答