我有一个复杂的类型:
[DataContract]
public class CustomClass
{
[DataMember]
public string Foo { get; set; }
[DataMember]
public int Bar { get; set; }
}然后我有一个WCF RESTful WCF服务,其中包含以下内容:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/class/save")]
bool Save(CustomClass custom);所以在浏览器端,我将我的CustomClass对象jsonized成如下所示:
var myClass = "{ foo: \"hello\", bar: 2 }";
$.ajax({
contentType: "application/json",
data: { custom: myClass },
dataType: "json",
success: callback,
type: "POST",
url: "MyService.svc/class/save"
});我使用$.ajax使用jquery提交数据,这样我就可以手动将内容类型设置为"application/json“,当它提交时,postbody看起来像这样
custom=<uri encoded version of myClass>我得到以下错误:
服务器在处理请求时遇到错误。异常消息是“检查MyAssembly.CustomClass类型的对象的开始元素时出错。遇到意外字符‘c’。”有关更多详细信息,请参阅服务器日志。异常堆栈跟踪是:在System.Runtime.Serialization.XmlObjectSerializer.IsStartObjectHandleExceptions (在System.Runtime.Serialization.Json.DataContractJsonSerializer.IsStartObject(XmlDictionaryReader读取器)在System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.ReadObject(Message消息)在System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.DeserializeRequest(Message消息,在System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message消息,Object[]参数)在System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message消息,在System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message消息处的Object[]参数),对象[]参数)在System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)在System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet的MessageRpc和rpc)
我已经尝试包装我的json化数据……我已经尝试使用$.post发送消息(但这并没有将contenttype设置为..any/json,所以webservice无法理解)..any想法?
发布于 2011-12-05 14:54:20
问题是您已经正确地转义了对象,但是当您在Json post方法中构建复杂的jQuery对象时,您无法转义包装器。所以你需要像这样转义整个JS对象:"{ \"custom\":\"{ foo:\"hello\",bar: 2 }\"}“(我自己实际上没有尝试过,但应该可以工作),或者(可能更好的解决方案)使用JSON.stringify({ custom: myClass })
WCF对它接收的用于序列化的JSON对象非常敏感。
发布于 2010-10-29 01:30:45
因此,您遇到的问题是序列化错误。WCF希望看到用"“包装的JSON中的属性名称
所以我遇到了同样的错误
data:'{id: 1 }',不起作用,但是
data:'{"id": 1 }',确实起作用了
我希望这能帮助其他人。
发布于 2009-11-26 11:45:25
https://stackoverflow.com/questions/1123093
复制相似问题