WCF列表数据成员

时间:2014-03-03 06:43:46

标签: c# wcf

我有一个WCF API需要像这样返回一个Json响应:

  {
      "Status":"ERR",
      "Errors":[
           {"Code":"Err_Auth_NoInfo"}
           "Message":"There has been an error with the settings of this website. Please         contact us as soon as possible to get your issue resolved"
        ]
    }

我的DataContract:

 [DataContract]
 public class Response
 {        
     [DataMember(Order = 0, IsRequired = false, EmitDefaultValue = false)]
     public List<error> Errors { get; set; }
 }
 public class error
 {
     [DataMember]
     public string Code { get; set; }
     [DataMember]
     public string Message { get; set; }
 }

我如何在我的方法中组建一个类来返回数据?我试过了

 Response info = new Response();
 error e = new error();
 e.Code = "test code";
 e.Message = "test message";
 info.Errors = new List<error>();

但这不起作用。

2 个答案:

答案 0 :(得分:1)

首先,您的Response对象没有属性Status,您应该添加它:

[DataContract]
public class Response
{
    [DataMember(Order = 0)]
    public string Status { get; set; }        

    [DataMember(Order = 1, IsRequired = false, EmitDefaultValue = false)]
    public List<Error> Errors { get; set; }
}

其次,您的Error课程缺少[DataContract]属性,您还应该添加它:

[DataContract]
public class Error
....

现在您可以像这样创建Response

Error e = new Error
{
    Code = "Test code",
    Message = "Test Message"
};
Response response = new Response
{
    Status = "ERR",
    Errors = new List<Error> { e }
};
return response;

答案 1 :(得分:0)

试试这个:

[DataContract]
public class Response
{        
    [DataMember(Order = 0, IsRequired = false, EmitDefaultValue = false)]
    public List<error> Errors { get; set; }

    public override string ToString()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(this);
    }
}
System.Web.Script.Serialization 类中提供了

JavaScriptSerializer

在您的服务实施方法实施中,执行以下操作:将返回类型更改为字符串并调用这些行。

//Your code here.
return myResponse.ToString();