我应该为WCF服务使用什么JSON

时间:2012-01-27 00:37:19

标签: wcf json

我正在使用这些方法运行WCF服务,

public string UploadInspections(Inspection[] inspections)
public string UploadInspection(Inspection inspection)

[DataContract]
public partial class Inspection
{
    [DataMember]
    public DateTime DateTime { get; set; }

    [DataMember]
    public int  Id { get; set; }

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

    [DataMember]
    public int Rating { get; set; }
}

从javascript我尝试使用JSON调用这些方法的POST。我用于UploadInspection方法的JSON就是这个,

{"Id":10,"Comment":"New One","Rating":3}

调用了UploadInspection方法,但检查对象设置为null。

我不确定如何使用JSON指定Date字段,我想也许解析器不喜欢没有Date字段的JSON。我从Inspection对象中删除了Date字段,但发生了同样的事情。

对于作为数组的UploadInspections方法,JSON应该是什么样的?我尝试了一些JSON,

"inspections": [{"Id":10,"Comment":"New One","Rating":3}]

还有这个,

[{"Id":10,"Comment":"New One","Rating":3}, {"Id":11,"Comment":"New Two","Rating":2}]

但是我收到了这个错误,

OperationFormatter encountered an invalid Message body. Expected to find an attribute with name 'type' and value 'object'. Found value 'string'.

1 个答案:

答案 0 :(得分:9)

问题不是我想的那样,在我的服务定义中,它最初看起来像这样,

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string UploadInspections(Inspection[] inspections);

删除后,

BodyStyle = WebMessageBodyStyle.WrappedRequest

有效!