c# – 使用WCF将类序列化为xsd.exe生成的JSON
|
我想用WCF编写RESTful Webservice,它能够以
JSON和XML进行回复.我有一个XML模式,我通过使用xsd.exe生成我的类.只要我请求XML,Everthing就可以正常工作,但如果我想要JSON作为响应,它就会失败.
System.ServiceModel.Dispatcher.MultiplexingDispatchMessageFormatter抛出System.Collections.Generic.KeyNotFoundException.问题是,到目前为止我发现,xsd.exe不生成DataContract和DataMember属性.是否有任何解决方案,我不需要使用SvcUtil.exe,因为我需要更改我的架构.. 这是失败的代码,JsonDispatchMessageFormatter的类型为MultiplexingDispatchMessageFormatter. (无论如何,这是默认类型) var headers = requestProperty.Headers[HttpRequestHeader.Accept] ?? requestProperty.Headers[HttpRequestHeader.ContentType];
if (headers != null && headers.Contains("application/json"))
{
return this.JsonDispatchMessageFormatter.SerializeReply(messageVersion,parameters,result);
}
生成的代码: [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd","4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="...")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="...",IsNullable=false)]
public partial class Incident {
private long incidentIdField;
/// <remarks/>
public long IncidentId {
get {
return this.incidentIdField;
}
set {
this.incidentIdField = value;
}
}
}
解决方法
您在JSON中看到私有字段而不是公共属性的原因是xsd.exe已使用
[SerializableAttribute]标记了您的类.当此属性应用于某个类型时,它表示可以通过序列化所有私有和类型来序列化该类型的实例.公共领域 – 不是属性.
在幕后,WCF使用 有点奇怪的是, 不幸的是,我没有看到任何 >从生成的类中删除[System.SerializableAttribute()].除非你在某处使用BinaryFormatter,否则这应该是无害的;你可能不是. 另外,如果您想要精确控制XML和JSON格式,WCF休息可能不是最适合您的技术. ASP.NET Web API允许使用json.net更精确地控制序列化格式;见JSON and XML Serialization in ASP.NET Web API以及Setting IgnoreSerializableAttribute Globally in Json.net和.NET WebAPI Serialization k_BackingField Nastiness. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
