2013-08-06 18 views
0

我試圖找出返回以下JSON字符串最簡單的方法:WCF服務返回簡單的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

您可以使用[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(); 
    } 
} 
+0

我不應該問關於SO的問題,當我幾乎半睡着了,一隻眼睛只能工作。我知道這一點。謝謝! – fuzz