質問

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?

役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top