【发布时间】:2011-10-06 23:16:27
【问题描述】:
我们正在使用 JSON.net,并希望使用一致的方式来发送和接收数据(文档)。
我们想要一个所有文档都派生自的基类。基类将具有 DocumentType 属性 - 这本质上是类名。
当客户端将此 json 序列化文档发布到服务器时,我们希望对其进行反序列化并确保客户端指定的 DocumentType 与服务器上的 ExpectedDocumentType 匹配。
除此之外,当此文档由服务器序列化并发送到客户端时,我们希望将 DocumentType 属性包含在 JSON 中 - 诀窍是我们希望此值是 ExpectedDocumentType 的值。
我尝试过这样做...如果 JsonProperty 和 JsonIgnore 属性仅在序列化期间生效而不是反序列化期间生效,那么这将起作用,但不幸的是,情况并非如此。
public abstract class JsonDocument
{
/// <summary>
/// The document type that the concrete class expects to be deserialized from.
/// </summary>
//[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types.
public abstract string ExpectedDocumentType { get; }
/// <summary>
/// The actual document type that was provided in the JSON that the concrete class was deserialized from.
/// </summary>
[JsonIgnore] // We ignore this property when serializing derived types and instead use the ExpectedDocumentType property.
public string DocumentType { get; set; }
}
有谁知道如何做到这一点?
本质上,逻辑是客户端可以提供任何 DocumentType,因此在反序列化期间服务器需要确保它与 ExpectedDocumentType 匹配,然后在序列化期间,当服务器将此文档发送给客户端时,服务器知道正确的 DocumentType,因此需要用 ExpectedDocumentType 填充它。
【问题讨论】:
-
你在使用 WCF 吗?还是只是对 ASHX 或 ASPX 的普通旧请求?