0

I have a WCF service which needs to return a Json response:

{
"Content": {
"Id": 817
"Message":"message"
},
"Status": "Ok"
}

Here the message parameter is optional in some cases it exists and in some it doesn't. I tried to get it working using following DataContract. But it doesn't seem to work. I get a response containing message as null in each and every response.

[DataContract]
public class CreateNewCandidate_Response
{
    [DataMember(Order=0, IsRequired=true)]
    public string Status { get; set; }
    [DataMember(Order = 1, IsRequired = false, EmitDefaultValue = false)]
    public CreateNewCandidate_Response_Content Content { get; set; }
    [DataMember(Order = 1, IsRequired = false, EmitDefaultValue = false)]
    public error Errors { get; set; }

}

public class error
{
    [DataMember(Order = 0)]
    public string Code { get; set; }
    [DataMember(Order = 1, IsRequired = false, EmitDefaultValue = false)]
    public string Message { get; set; }
}

public class CreateNewCandidate_Response_Content
{
    [DataMember(Order = 0, IsRequired = true, EmitDefaultValue = true)]
    public int CandidateId { get; set; }
    [DataMember(Order = 0, IsRequired = false, EmitDefaultValue = false)]
    public string Message { get; set; }
}

How can I get it to return response in the format I want?

Arti
  • 2,993
  • 11
  • 68
  • 121
  • 2
    I don't know if it's going to fix the problem, but also decorate the Error and CreateNewCandidate_Response_Content classes with the [DataContract] attribute. – Bart Beyers Mar 04 '14 at 08:35

1 Answers1

2

The short answer is: Bart Beyers is correct, apply the [DataContract] attribute.

The long anser is taken from MSDN:

New complex types that you create must have a data contract defined for them to be serializable. By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized.

http://msdn.microsoft.com/en-us/library/ms733127%28v=vs.110%29.aspx

toATwork
  • 1,335
  • 16
  • 34