CollectionDataContract用于使用Json数组

时间:2013-03-11 16:21:14

标签: .net json wcf datacontract

假设服务产生了这个json:

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

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

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

1 个答案:

答案 0 :(得分: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();
    }
}