2013-03-11 52 views
3

假设有此JSON由服务产生:CollectionDataContract到用于消耗JSON数组

[{"key1": 12, "key2": "ab"}, {"key1": 10, "key2": "bc"}] 

是这可能通过WCF其余进行检索和使用CollectionDataContract解析为一个列表然后再次自动地与DataContract解析?

我试图这样做,但总是给人“根级别无效,1号线,位置1”

+0

请告诉你如何试图解析它,它可能是你只是稍微偏离并在这里多余的眼睛可以告诉你的剩下的路 – curtisk 2013-03-11 17:18:03

回答

3

没有什么特别之处[CDC]和JSON - 它应该只是工作 - 看下面的代码。尝试将其与您的网站进行比较,包括网络跟踪(如Fiddler等工具中所见),并查看有何不同。

public class StackOverflow_15343502 
{ 
    const string JSON = "[{\"key1\": 12, \"key2\": \"ab\"}, {\"key1\": 10, \"key2\": \"bc\"}]"; 
    public class MyDC 
    { 
     public int key1 { get; set; } 
     public string key2 { get; set; } 

     public override string ToString() 
     { 
      return string.Format("[key1={0},key2={1}]", key1, key2); 
     } 
    } 

    [CollectionDataContract] 
    public class MyCDC : List<MyDC> { } 

    [ServiceContract] 
    public class Service 
    { 
     [WebGet] 
     public Stream GetData() 
     { 
      WebOperationContext.Current.OutgoingResponse.ContentType = "application/json"; 
      return new MemoryStream(Encoding.UTF8.GetBytes(JSON)); 
     } 
    } 

    [ServiceContract] 
    public interface ITest 
    { 
     [WebGet(ResponseFormat = WebMessageFormat.Json)] 
     MyCDC GetData(); 
    } 

    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"); 

     WebChannelFactory<ITest> factory = new WebChannelFactory<ITest>(new Uri(baseAddress)); 
     ITest proxy = factory.CreateChannel(); 
     var result = proxy.GetData(); 
     Console.WriteLine(string.Join(", ", result)); 
     ((IClientChannel)proxy).Close(); 
     factory.Close(); 

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