Question

I have a WCF API which needs to return a Json response like this:

  {
      "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"
        ]
    }

My 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; }
 }

How will I have to form a class to return data in my method? I tried it

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

But this isn't working.

Was it helpful?

Solution

First of all, your Response object doesn't have a property Status, you should add it:

[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; }
}

Secondly your Error class is missing the [DataContract] attribute, you should also add it:

[DataContract]
public class Error
....

Now you can create your Response like this:

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

OTHER TIPS

Try this:

[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);
    }
}

JavaScriptSerializer is available in System.Web.Script.Serialization class.

In your Service implementation method implementation, do this: Change the return type to string and call these lines.

//Your code here.
return myResponse.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top