【问题标题】:WCF Service to return simple JSON resultWCF 服务返回简单的 JSON 结果
【发布时间】:2013-08-06 13:06:32
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: c# json wcf service


    【解决方案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();
        }
    }
    

    【讨论】:

    • 当我几乎半睡半醒并且一只眼睛只能工作时,我不应该问关于 SO 的问题。我知道这一点。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多