wcf json-response阵列/列表

时间:2012-07-30 16:06:23

标签: json wcf

我正在开发一个wcf-webservice。消费者能够在原子响应和json响应之间进行选择。

我的OperationContract看起来像这样:

[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "json/json")]
    Result GetData();

Result-Type包含一些字符串和一系列条目。

 [DataContract]
public class Result
{
    [DataMember]
    public string baseUrl;
    [DataMember]
    public string url;
    [DataMember]
    public string title;
    [DataMember]
    public int totalResults;
    [DataMember]
    public JsonEntries[] resources;
}

我将JsonEntries也标记为DataContract:

  [DataContract]
public class JsonEntries
{
    [DataMember]
    public string updated;
    [DataMember]
    public string key;
    [DataMember]
    public string title;
    [DataMember]
    public Salary salarie;
}

但是,当我尝试运行此操作时,我收到错误,无法调用元数据。当我删除数组前面的[DataMember]时,我没有收到错误,但我的响应不包含数组。 我已经看到它在各种exmaples上都是这样的。我做错了什么?

提前感谢。

robidd

1 个答案:

答案 0 :(得分:1)

应该可行,这是我的代码示例

DataContracts

[DataContract]
public class Result
{
    [DataMember]
    public int totalResults;
    [DataMember]
    public JsonEntries[] resources;
}

[DataContract]
public class JsonEntries
{
    [DataMember]
    public string title;
}

OperationContract的

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getdata")]
Result GetData();

    public Result GetData()
    {
        var jsonEntries = new List<JsonEntries>
            {
                new JsonEntries {title = "1"},
                new JsonEntries {title = "2"},
                new JsonEntries {title = "3"}
            }.ToArray();
        return new Result
        {
            resources = jsonEntries,
            totalResults = 1
        };
    }

我接到电话

    private Bag<T> GetData<T>(string uri)
    {
        try
        {
            var request = (HttpWebRequest) WebRequest.Create(uri);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.Headers[HttpRequestHeader.Authorization] = _authorizationData;
            var response = (HttpWebResponse) request.GetResponse();
            Stream stream = response.GetResponseStream();
            var localStream = new MemoryStream();
            CopyStream(stream, localStream);
            stream.Close();
            var result = JsonContractExtensions.Create<T>(localStream);
            return new Bag<T>(result);
        }
        catch (WebException ex)
        {
            _log.Debug(ex);
            return Bag<T>.Empty;
        }
        catch (Exception ex)
        {
            _log.Debug(ex);
            return Bag<T>.Empty;
        }
    }