C#JSON自定义结果列表名称

时间:2017-06-07 09:59:20

标签: c# json wcf

如何将< MethodName>结果中的C#的JSON响应覆盖到类名?

它始终返回methodname + Results。我有办法将其更改为类名吗?

或者我在代码上做错了什么?

这是我的Exchange_Reason类

[DataContract]
public class Exchange_Reason
{
    [DataMember]
    public string Exchange_Reason_ID { get; set; }

    [DataMember]
    public string Reason { get; set; }

    [DataMember]
    public string Status { get; set; }
}

我的服务合同

[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getExchange_Reason_List")]
    List<Exchange_Reason> GetExchange_Reason_List();

实施

public List<Exchange_Reason> GetExchange_Reason_List()
{
     List<Exchange_Reason> results = new List<Exchange_Reason>();
     ...
     while (reader.Read())
     {
           results.Add(new Exchange_Reason()
           {
                 Exchange_Reason_ID = reader["Exchange_Reason_ID"].ToString(),
                 Reason = reader["Reason"].ToString(),
                 Status = reader["Status"].ToString()
           });
     }
     return results;
}

结果

{
    GetExchange_Reason_ListResult: [
        {
            Exchange_Reason_ID: "1000001",
            Reason: "Rotten",
            Status: "Active"
        },
        {
            Exchange_Reason_ID: "1000002",
            Reason: "Expired",
            Status: "Active"
        }
    ]
}

我需要它:

{
    Exchange_Reasons: [
        {
            Exchange_Reason_ID: "1000001",
            Reason: "Rotten",
            Status: "Active"
        },
        {
            Exchange_Reason_ID: "1000002",
            Reason: "Expired",
            Status: "Active"
        }
    ]
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

因为你的BodyStyle被包裹了。首先从BodyStyle中删除WebInvoke,然后按照您想要的方式换行输出。我想你想要这个:

 [DataContract]
public class GetExchange_Reason_ListResult
{
    [DataMember]
    public Exchange_Reason[] Exchange_Reasons { get; set; }
}

public class Exchange_Reason
{
    public string Exchange_Reason_ID { get; set; }
    public string Reason { get; set; }
    public string Status { get; set; }
}

你的方法应该是这样的:

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getExchange_Reason_List")]
GetExchange_Reason_ListResult GetExchange_Reason_List();