3

假设有一个服务产生了这个 json:

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

这是否可以由 wcf rest 检索并使用 CollectionDataContract 作为列表进行解析,然后使用 DataContract 再次自动解析?

我试过这样做,但总是给出“根级别无效,第 1 行,位置 1”

4

1 回答 1

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();
    }
}
于 2013-03-11T17:34:59.757 回答